forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.java
More file actions
69 lines (66 loc) · 2.32 KB
/
3Sum.java
File metadata and controls
69 lines (66 loc) · 2.32 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
67
68
69
//Do not use extra space, O(N^2), o(N)
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>> result
= new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < num.length; ++i){
for(int j = i + 1, k = num.length - 1; j < k;){
while(j < k - 1 && num[j] == num[j+1])
++j;
while(k > j + 1&& num[k] == num[k-1])
--k;
int sum = num[i] + num[j] + num[k];
if(sum > 0)
--k;
else if(sum < 0) j++;
else{
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[j]);
tmp.add(num[k]);
result.add(tmp);
++j;
--k;
}
}
while(i < num.length - 1 && num[i] == num[i+1])
++i;
}
return result;
}
}
//Use Extra Space (HashSet), O(N^2)
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>> result = new ArrayList<ArrayList<Integer>>();
HashSet<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();
for(int i = 0; i < num.length; i++){
for(int j = i + 1, k = num.length - 1; j < k;){
int sum = num[i] + num[j] + num[k];
if(sum > 0)
--k;
else if(sum < 0)
++j;
else{
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[j]);
tmp.add(num[k]);
if(!set.contains(tmp)){
set.add(tmp);
result.add(tmp);
}
++j;
--k;
}
}
}
return result;
}
}