forked from jieli4970/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSumTwoPointer.java
More file actions
30 lines (28 loc) · 870 Bytes
/
ThreeSumTwoPointer.java
File metadata and controls
30 lines (28 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.Arrays;
public class ThreeSumTwoPointer implements ThreeSum {
@Override
public int count(int[] nums) {
int N = nums.length;
int cnt = 0;
Arrays.sort(nums);
for (int i = 0; i < N - 2; i++) {
int l = i + 1, h = N - 1, target = -nums[i];
if (i > 0 && nums[i] == nums[i - 1]) continue;
while (l < h) {
int sum = nums[l] + nums[h];
if (sum == target) {
cnt++;
while (l < h && nums[l] == nums[l + 1]) l++;
while (l < h && nums[h] == nums[h - 1]) h--;
l++;
h--;
} else if (sum < target) {
l++;
} else {
h--;
}
}
}
return cnt;
}
}