-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSum3.java
More file actions
73 lines (50 loc) · 1.3 KB
/
Sum3.java
File metadata and controls
73 lines (50 loc) · 1.3 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
70
71
72
73
import java.util.ArrayList;
import java.util.Arrays;
public class Sum3 {
public static void main(String[] args){
int[] num = {0,0,0};
ArrayList<ArrayList<Integer>> hehe = threeSum(num);
for (int i =0; i<hehe.size();i++){
System.out.println(hehe.get(i).toString());
}
}
public static ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();
if (num.length < 3)
return all;
Arrays.sort(num);
int first = 0;
int last = num.length - 1;
while(first < last){
int middle = first + 1;
while(middle < last){
int sum = num[first]+num[middle]+num[last];
if(sum == 0){
ArrayList<Integer> sub = new ArrayList<Integer>();
sub.add(new Integer(num[first]));
sub.add(new Integer(num[middle]));
sub.add(new Integer(num[last]));
all.add(sub);
}
if (sum > 0){
last = last -1;
while (last>first&&num[last] == num[last+1]){
last = last -1;
}
}
if (sum <= 0){
middle = middle +1;
while(middle<last&&num[middle]==num[middle-1]){
middle ++;
}
}
}
first++;
while(first<last&&num[first] == num[first-1]){
first++;
}
last =num.length - 1;
}
return all;
}
}