forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4Sum.java
More file actions
66 lines (57 loc) · 1.83 KB
/
4Sum.java
File metadata and controls
66 lines (57 loc) · 1.83 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
58
59
60
61
62
63
64
65
66
// use hashtable, worst case will still be O(n^3)
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> ilist = new ArrayList<Integer>();
if(num.length<4) return res;
Arrays.sort(num);
Map<Integer, ArrayList<Integer>> hash = new HashMap<Integer, ArrayList<Integer>>();
ArrayList<Integer> tlist = new ArrayList<Integer>();
for(int i=0; i<num.length; i++)
for(int j=i+1; j<num.length; j++){
int tempint = target-num[i]-num[j];
tlist.clear();
if(hash.containsKey(tempint))
tlist = hash.get(tempint);
tlist.add(i);
tlist.add(j);
hash.put(tempint,(ArrayList<Integer>)tlist.clone());
}
int p,q;
int p_value = Integer.MAX_VALUE;
int q_value;
for(p=0; p<num.length-3; p++){
if(num[p]==p_value)
continue;
q = p+1;
p_value = num[p];
while(q<num.length-2){
q_value = num[q];
int s = num[p] + num[q];
if(hash.containsKey(s)){
ArrayList<Integer> t = hash.get(s);
int count =Integer.MAX_VALUE;
for(int x=0; x<t.size()-1; x+=2){
if(t.get(x)<=q || (x>count && num[t.get(x-2)]==num[t.get(x)] && num[t.get(x-1)]==num[t.get(x+1)])){
continue;
}
else{
ilist.clear();
ilist.add(num[p]);
ilist.add(num[q]);
ilist.add(num[t.get(x)]);
ilist.add(num[t.get(x+1)]);
res.add((ArrayList<Integer>)ilist.clone());
count = x;
}
}
}
while(++q<num.length-2 && num[q]==q_value);
}
}
return res;
}
}