-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSum.java
More file actions
93 lines (88 loc) · 2.37 KB
/
ThreeSum.java
File metadata and controls
93 lines (88 loc) · 2.37 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j !=
//k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。
//
// 注意:答案中不可以包含重复的三元组。
//
//
//
//
//
// 示例 1:
//
//
//输入:nums = [-1,0,1,2,-1,-4]
//输出:[[-1,-1,2],[-1,0,1]]
//解释:
//nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
//nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
//nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
//不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
//注意,输出的顺序和三元组的顺序并不重要。
//
//
// 示例 2:
//
//
//输入:nums = [0,1,1]
//输出:[]
//解释:唯一可能的三元组和不为 0 。
//
//
// 示例 3:
//
//
//输入:nums = [0,0,0]
//输出:[[0,0,0]]
//解释:唯一可能的三元组和为 0 。
//
//
//
//
// 提示:
//
//
// 3 <= nums.length <= 3000
// -10⁵ <= nums[i] <= 10⁵
//
//
// 👍 7482 👎 0
package leetcode.editor.cn;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeSum{
public static void main(String[] args) {
Solution solution = new ThreeSum().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
int len = nums.length;
for (int i = 0; i < len - 2; i++) {
if (nums[i] + nums[i+1] + nums[i+2] > 0) break;
if (nums[i] + nums[len-2] + nums[len-1] < 0) continue;
if (i > 0 && nums[i] == nums[i-1]) continue;
int l = i + 1;
int r = len - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
ans.add(Arrays.asList(nums[i], nums[l], nums[r]));
do l++;
while (l < r && nums[l] == nums[l - 1]);
do r--;
while (l < r && nums[r] == nums[ r + 1]);
} else if (sum > 0) {
r--;
} else {
l++;
}
}
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}