forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum.java
More file actions
executable file
·49 lines (41 loc) · 1.4 KB
/
3sum.java
File metadata and controls
executable file
·49 lines (41 loc) · 1.4 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
/**
*/
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> numArr = new ArrayList<Integer>();
for(int i=0;i<num.length;i++){
numArr.add(num[i]);
}
Collections.sort(numArr);
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer> >();
for(int i=0;i<numArr.size();i++){
if(numArr.get(i)>0) break;
int j,k;
j = i+1;
k = numArr.size()-1;
while(j<k){
int tmpSum = numArr.get(i)+numArr.get(j)+numArr.get(k);
if(tmpSum<0){
j++;
}else if(tmpSum>0){
k--;
}else{
ArrayList<Integer> tmpArray = new ArrayList<Integer>();
tmpArray.add(numArr.get(i));
tmpArray.add(numArr.get(j));
tmpArray.add(numArr.get(k));
result.add(tmpArray);
j++;
k--;
}
}
}
HashSet<ArrayList<Integer>> tmpset = new HashSet<ArrayList<Integer>>(result);
result = new ArrayList<ArrayList<Integer>>(tmpset);
return result;
}
}