-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathThreeSum.java
More file actions
46 lines (44 loc) · 1.44 KB
/
Copy pathThreeSum.java
File metadata and controls
46 lines (44 loc) · 1.44 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
package leetcode.array.problem15;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created with IntelliJ IDEA
*
* @Author yuanhaoyue swithaoy@gmail.com
* @Description 15. 3Sum 三数之和
* @Date 2018-12-14
* @Time 1:21
*/
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) {
break;
}
if (i == 0 || nums[i] != nums[i - 1]) {
int num = 0 - nums[i], low = i + 1, high = nums.length - 1;
while (low < high) {
if (nums[low] + nums[high] == num) {
result.add(Arrays.asList(nums[i], nums[low], nums[high]));
while (low < high && nums[low] == nums[low + 1]) {
low++;
}
while (low < high && nums[high] == nums[high - 1]) {
high--;
}
low++;
high--;
} else if (nums[low] + nums[high] > num) {
high--;
} else if (nums[low] + nums[high] < num) {
low++;
}
}
}
}
return result;
}
}