-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy path3sum.java
More file actions
51 lines (42 loc) · 1.45 KB
/
3sum.java
File metadata and controls
51 lines (42 loc) · 1.45 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
import java.util.ArrayList;
import java.util.Hashtable;
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
Arrays.sort(num);
ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
int i,j,p;
int i_value = Integer.MAX_VALUE;
int j_value, p_value;
int sum;
for(i=0; i<num.length-2; i++){
if(num[i] == i_value)
continue;
i_value = num[i];
p = i+1;
j = num.length-1;
while(p<j){
sum = num[i]+num[p]+num[j];
j_value = num[j];
p_value = num[p];
if(sum>0){
while(--j>p && num[j] == j_value);
}
else if(sum == 0){
temp.clear();
temp.add(num[i]);
temp.add(num[p]);
temp.add(num[j]);
re.add((ArrayList<Integer>)temp.clone());
while(++p<j && num[p] == p_value);
}
else{
while(++p<j && num[p] == p_value);
}
}
}
return re;
}
}