-
Notifications
You must be signed in to change notification settings - Fork 0
/
4Sum.java
64 lines (59 loc) · 1.72 KB
/
4Sum.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> q=new ArrayList<>();
int n=nums.length;
for(int i=0;i<n-3;i++)
{
if(i>0&&nums[i]==nums[i-1])
{
continue;
}
for(int j=i+1;j<n;j++)
{
if(j>i+1&&nums[j]==nums[j-1])
{
continue;
}
int k=j+1;
int l=n-1;
while(k<l)
{
long sum = nums[i];
sum += nums[j];
sum += nums[k];
sum += nums[l];
if(target==sum)
{
ArrayList<Integer> al=new ArrayList<>();
al.add(nums[i]);
al.add(nums[j]);
al.add(nums[k]);
al.add(nums[l]);
Collections.sort(al);
q.add(al);
k++;
l--;
while(k<l&&nums[l]==nums[l+1])
{
l--;
}
while(k<l&&nums[k]==nums[k-1])
{
k++;
}
}
else if(sum<target)
{
k++;
}
else
{
l--;
}
}
}
}
return q;
}
}