forked from dongfeiwww/abc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.java
More file actions
45 lines (44 loc) · 1.41 KB
/
3Sum.java
File metadata and controls
45 lines (44 loc) · 1.41 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
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
if(num.length<3) return result;
Arrays.sort(num);
for(int i=0; i<=num.length-3; i++)
{
if(i!=0 && num[i]==num[i-1]) continue;
int sum=-num[i];
int start=i+1, end=num.length-1;
while(start<end)
{
int temp=num[start]+num[end];
if(temp==sum)
{
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(num[i]);
list.add(num[start]);
list.add(num[end]);
result.add(list);
start++;
while(start<end && num[start]==num[start-1])
{
start++;
}
end--;
while(start<end && num[end]==num[end+1])
{
end--;
}
}else if(temp>sum)
{
end--;
}else
{
start++;
}
}
}
return result;
}
}