Skip to content

Commit eda9fd9

Browse files
committed
leetcode15
1 parent bafa174 commit eda9fd9

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
+ [509. 斐波那契数](leetcode/509.md)
3434
+ [191. 位1的个数](leetcode/191.md)
3535
+ [283. 移动零](leetcode/283.md)
36-
+ [E70. 爬楼梯](leetcode/70.md)
36+
+ [70. 爬楼梯](leetcode/70.md)
3737

3838
### Medium
3939

@@ -42,6 +42,7 @@
4242
+ [343. 整数拆分](leetcode/343.md)
4343
+ [50. Pow(x, n)](leetcode/50.md)
4444
+ [11. 盛最多水的容器](leetcode/11.md)
45+
+ [15. 三数之和](leetcode/15.md)
4546

4647
### Hard
4748

@@ -55,6 +56,7 @@
5556

5657
+ [M11. 盛最多水的容器](leetcode/11.md)
5758
+ [E283. 移动零](leetcode/283.md)
59+
+ [M15. 三数之和](leetcode/15.md)
5860
+ [E217. 存在重复元素](leetcode/217.md)
5961
+ [M240. 搜索二维矩阵 II](leetcode/240.md)
6062
+ [M79. 单词搜索](leetcode/79.md)

leetcode/15.md

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# 15. 三数之和
2+
3+
## 题目描述
4+
5+
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
6+
7+
注意:答案中不可以包含重复的三元组。
8+
9+
10+
11+
## 示例
12+
13+
示例 1:
14+
15+
```
16+
给定数组 nums = [-1, 0, 1, 2, -1, -4],
17+
18+
满足要求的三元组集合为:
19+
[
20+
[-1, 0, 1],
21+
[-1, -1, 2]
22+
]
23+
```
24+
25+
26+
27+
# Code
28+
29+
双指针
30+
31+
```java
32+
class Solution {
33+
public List<List<Integer>> threeSum(int[] nums) {
34+
List<List<Integer>> res = new ArrayList<>();
35+
int len = nums.length;
36+
//前提判断
37+
if (nums == null || len < 3) return res;
38+
//排序(nlogn)
39+
Arrays.sort(nums);
40+
for (int i = 0; i < len - 2; i++) {
41+
if(nums[i] > 0) return res;
42+
//重复情况排除
43+
if (i != 0 && nums[i] == nums[i -1]) continue;
44+
int head = i + 1, tail = len - 1;
45+
while (head < tail) {
46+
int s = nums[i] + nums[head] + nums[tail];
47+
if(s < 0) {
48+
//排除重复项
49+
while(head < tail && nums[head] == nums[++head]);
50+
} else if (s > 0) {
51+
//排除重复项
52+
while(head < tail && nums[tail] == nums[--tail]);
53+
} else {
54+
res.add(new ArrayList<>(Arrays.asList(nums[i], nums[tail], nums[head])));
55+
while(head < tail && nums[head] == nums[++head]) ;
56+
while(head < tail && nums[tail] == nums[--tail]) ;
57+
}
58+
}
59+
}
60+
return res;
61+
}
62+
63+
}
64+
```
65+
66+
**复杂度分析**
67+
68+
- 时间复杂度 O(N^2)
69+
- 空间复杂度 O(1)
70+
71+
# 题解
72+
73+
https://leetcode-cn.com/problems/3sum/solution/3sumpai-xu-shuang-zhi-zhen-yi-dong-by-jyd/

0 commit comments

Comments
 (0)