-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy path3sum.java
26 lines (24 loc) · 835 Bytes
/
3sum.java
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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums.length<3) return result;
Arrays.sort(nums);
for(int i=0; i+2<nums.length; i++){
if(i>0 && nums[i] == nums[i-1])
continue;
int j=i+1, k=nums.length - 1;
int target = -nums[i];
while(j<k){
if(nums[j]+nums[k] == target){
result.add(Arrays.asList(nums[i],nums[j],nums[k]));
j++; k--;
while(j<k && nums[j] == nums[j-1]) j++;
while(j<k && nums[k] == nums[k+1]) k--;
}
else if(nums[j]+nums[k] > target) k--;
else j++;
}
}
return result;
}
}