-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfour4Sum.java
More file actions
57 lines (47 loc) · 1.43 KB
/
Copy pathfour4Sum.java
File metadata and controls
57 lines (47 loc) · 1.43 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
54
55
56
57
package LeetCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class four4Sum {
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> resList = new ArrayList<List<Integer>>();
Set<List<Integer>> res = new HashSet<List<Integer>>();
int len = nums.length,first , second, third,fourth;
Arrays.sort(nums);
for(int i=0;i<len-3;i++){
for(int j=i+1;j<len-2;j++){
first = i;
second = j;
third = second+1;
fourth = len-1;
while(third < fourth){
if(nums[first] + nums[second] + nums[third] + nums[fourth]== target){
List<Integer> temp = new ArrayList<Integer>();
temp.add(nums[first]);
temp.add(nums[second]);
temp.add(nums[third]);
temp.add(nums[fourth]);
res.add(temp);
third++;
fourth--;
}
else if(nums[first] + nums[second] + nums[third]+ nums[fourth]< target)
third++;
else if(nums[first] + nums[second] + nums[third]+ nums[fourth] > target)
fourth--;
}
}
}
resList.addAll(res);
return resList;
}
public static void main(String[] args) {
int[] arr = {0,0,0,0};
List<List<Integer>> res = fourSum(arr,1);
for(int i=0;i<res.size();i++){
System.out.println(res.get(i).toString());
}
}
}