-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.三数之和.java
63 lines (58 loc) · 1.92 KB
/
15.三数之和.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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/*
* @lc app=leetcode.cn id=15 lang=java
*
* [15] 三数之和
*/
// @lc code=start
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
return nSum(nums, 0, 3, 0);
}
private List<List<Integer>> nSum(int[] nums, int start, int n, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length < n || n < 2)
return res;
if (n == 2) {
int left = start;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
int low = nums[left];
int high = nums[right];
if (sum < target) {
while (nums[left] == low && left < right)
left++;
} else if (sum > target) {
while (nums[right] == high && left < right)
right--;
} else {
List<Integer> rList = new ArrayList<>();
rList.add(nums[left]);
rList.add(nums[right]);
res.add(rList);
while (nums[left] == low && left < right)
left++;
while (nums[right] == high && left < right)
right--;
}
}
} else {
for (int i = start; i < nums.length; i++) {
List<List<Integer>> result = nSum(nums, i + 1, n - 1, target - nums[i]);
for (List<Integer> list : result) {
list.add(0, nums[i]);
res.add(list);
}
while (i < nums.length - 1 && nums[i] == nums[i + 1])
i++;
}
}
return res;
}
}
// @lc code=end