-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFourSum.java
48 lines (40 loc) · 1.4 KB
/
FourSum.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.*;
public class FourSum {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans=new ArrayList<>();
Arrays.sort(nums);
for(int i=0;i<nums.length-3;i++)
{
for(int j=i+1;j<nums.length-2;j++)
{
long res = (nums[i] + nums[j]);
long remaining = target - res;
int left=j+1;
int right=nums.length-1;
while(left<right)
{
long sum=nums[left]+nums[right];
if( sum == remaining)
{
ArrayList<Integer> temp=new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[left]);
temp.add(nums[right]);
if(!ans.contains(temp))ans.add(temp);
left++;
right--;
}
else if(sum<remaining)
{
left++;
}
else if(sum>remaining){
right--;
}
}
}
}
return ans;
}
}