auto commit
This commit is contained in:
28
notes/算法.md
28
notes/算法.md
@ -115,21 +115,19 @@ public class ThreeSumFast {
|
||||
```
|
||||
|
||||
```java
|
||||
public class ThreeSumFast implements ThreeSum {
|
||||
@Override
|
||||
public int count(int[] nums) {
|
||||
Arrays.sort(nums);
|
||||
int N = nums.length;
|
||||
int cnt = 0;
|
||||
for (int i = 0; i < N; i++)
|
||||
for (int j = i + 1; j < N; j++) {
|
||||
int target = -nums[i] - nums[j];
|
||||
int index = BinarySearch.search(nums, target);
|
||||
// 应该注意这里的下标必须大于 j,否则会重复统计。
|
||||
if (index > j)
|
||||
cnt++;
|
||||
}
|
||||
return cnt;
|
||||
public class BinarySearch {
|
||||
public static int search(int[] nums, int target) {
|
||||
int l = 0, h = nums.length - 1;
|
||||
while (l <= h) {
|
||||
int m = l + (h - l) / 2;
|
||||
if (target == nums[m])
|
||||
return m;
|
||||
else if (target > nums[m])
|
||||
l = m + 1;
|
||||
else
|
||||
h = m - 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user