avatar

day2三数之和

解法来自于leecode

题目:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<p>给你一个包含 <em>n</em> 个整数的数组&nbsp;<code>nums</code>,判断&nbsp;<code>nums</code>&nbsp;中是否存在三个元素 <em>a,b,c ,</em>使得&nbsp;<em>a + b + c = </em>0 ?请你找出所有满足条件且不重复的三元组。</p>

<p><strong>注意:</strong>答案中不可以包含重复的三元组。</p>

<p>&nbsp;</p>

<p><strong>示例:</strong></p>

<pre>给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
</pre>
<div><div>Related Topics</div><div><li>数组</li><li>双指针</li></div></div>

代码:

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
//给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复
//的三元组。
//
// 注意:答案中不可以包含重复的三元组。
//
//
//
// 示例:
//
// 给定数组 nums = [-1, 0, 1, 2, -1, -4],
//
//满足要求的三元组集合为:
//[
// [-1, 0, 1],
// [-1, -1, 2]
//]
//
// Related Topics 数组 双指针


//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList();
int len = nums.length;
if(nums == null || len < 3) return ans;
Arrays.sort(nums); // 排序
for (int i = 0; i < len ; i++) {
if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
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]));
while (L<R && nums[L] == nums[L+1]) L++; // 去重
while (L<R && nums[R] == nums[R-1]) R--; // 去重
L++;
R--;
}
else if (sum < 0) L++;
else if (sum > 0) R--;
}
}
return ans;

}
}
//leetcode submit region end(Prohibit modification and deletion)

图1

2

3

4

5

6

7

8

9

10

11

12

文章作者: 无知的小狼
文章链接: https://bytedance.press/2020/04/26/20200401/%E4%B8%89%E6%95%B0%E4%B9%8B%E5%92%8C/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 无知的小狼

评论