-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path18. 4Sum
39 lines (39 loc) · 1.41 KB
/
18. 4Sum
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
31
32
33
34
35
36
37
38
39
//O(n3) time and O(1) space
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList();
//Sanity Check
if(nums==null || nums.length<4) return list;
int n = nums.length;
Arrays.sort(nums);
for(int i=0;i<n-3;i++){
if(i>0 && nums[i]==nums[i-1]) continue;
for(int j=i+1;j<n-2;j++){
if(j>i+1 && nums[j]==nums[j-1]) continue;
int low = j+1, high = n-1;
while(low<high){
int sum = nums[i] + nums[j] + nums[low] + nums[high];
if(sum==target){
List<Integer> sublist = new ArrayList();
sublist.add(nums[i]);
sublist.add(nums[j]);
sublist.add(nums[low]);
sublist.add(nums[high]);
list.add(sublist);
while(low<high && nums[low]==nums[low+1]) low++;
while(low<high && nums[high]==nums[high-1]) high--;
low++;
high--;
}
else if(sum<target){
low++;
}
else{
high--;
}
}
}
}
return list;
}
}