-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4sum.java
More file actions
53 lines (48 loc) · 1.7 KB
/
4sum.java
File metadata and controls
53 lines (48 loc) · 1.7 KB
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
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
ArrayList<List<Integer>> arr = new ArrayList<List<Integer>>();
if(nums == null || nums.length ==0)
{
return arr;
}
int n = nums.length;
Arrays.sort(nums);
for(int i = 0;i<n;++i)
{
for(int j = i+1;j<n;++j)
{
int res = target - nums[i]-nums[j];
if(j+1<n)
{
int lef = j+1;
int rig = n-1;
while(lef<rig)
{
if(nums[lef]+nums[rig]<res)
++lef;
else if(nums[lef]+nums[rig]>res)
--rig;
else
{
List<Integer> indices = new ArrayList<Integer>();
indices.add(nums[i]);
indices.add(nums[j]);
indices.add(nums[lef]);
indices.add(nums[rig]);
arr.add(indices);
while(nums[lef] == indices.get(2) && lef<rig)
lef++;
while(nums[rig] == indices.get(3) && lef<rig)
rig--;
}
}
}
while(j+1<n && nums[j]==nums[j+1])
j++;
}
while(i+1<n && nums[i]==nums[i+1])
i++;
}
return arr;
}
}