-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution015.java
67 lines (57 loc) · 1.92 KB
/
Solution015.java
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
package algorithm.leetcode;
import java.util.*;
/**
* @author: mayuan
* @desc: 三数之和
* @date: 2018/07/10
*/
public class Solution015 {
public static void main(String[] args) throws Exception {
int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
int[] nums2 = new int[]{};
int[] nums3 = new int[]{0, 0, 0, 0};
System.out.println(new Solution015().threeSum(nums));
System.out.println(new Solution015().threeSum(nums2));
System.out.println(new Solution015().threeSum(nums3));
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> answer = new ArrayList<>();
if (null == nums || nums.length < 3) {
return answer;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) {
break;
}
int begin = i + 1;
int end = nums.length - 1;
// nums[i]和nums[i-1]相等,避免重复
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
while (begin < end) {
// nums[begin]和nums[begin-1]相等,避免重复
if (begin > i + 1 && nums[begin] == nums[begin - 1]) {
++begin;
continue;
}
// nums[end]和nums[end+1]相等,避免重复
if (end < nums.length - 1 && nums[end] == nums[end + 1]) {
--end;
continue;
}
int sum = nums[i] + nums[begin] + nums[end];
if (0 == sum) {
answer.add(Arrays.asList(nums[i], nums[begin], nums[end]));
++begin;
} else if (0 > sum) {
++begin;
} else {
--end;
}
}
}
return answer;
}
}