-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.java
More file actions
25 lines (25 loc) · 883 Bytes
/
3Sum.java
File metadata and controls
25 lines (25 loc) · 883 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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if(nums.length<3) return null;
Set<List<Integer>> mainList = new HashSet<>();
//sort the array
Arrays.sort(nums);
for(int i = 0;i<nums.length-2;i++){
int target = nums[i];
int low = i+1,high = nums.length-1;
while(low<high){
if(nums[low] + nums[high] == -target){
List<Integer> subList = new ArrayList<>();
subList.add(target);
subList.add(nums[low]);
subList.add(nums[high]);
mainList.add(subList);
low++;high--;
}
else if(nums[low] + nums[high] > -target) high--;
else low++;
}
}
return new ArrayList<>(mainList);
}
}