Skip to content

Commit c7c8c28

Browse files
committed
18
1 parent 1bc42c1 commit c7c8c28

3 files changed

+50
-1
lines changed

SUMMARY.md

+1
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@
1818
* [15. 3Sum](leetCode-15-3Sum.md)
1919
* [16. 3Sum Closest](leetCode-16-3Sum-Closest.md)
2020
* [17. Letter Combinations of a Phone Number](leetCode-17-Letter-Combinations-of-a-Phone-Number.md)
21+
* [18. 4Sum](leetCode-18-4Sum.md)
2122
* [79. Word Search](leetCode-79-Word-Search.md)

leetCode-17-Letter-Combinations-of-a-Phone-Number.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 题目描述
1+
# 题目描述(中等难度)
22

33
![](https://windliang.oss-cn-beijing.aliyuncs.com/17.jpg)
44

leetCode-18-4Sum.md

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# 题目描述(中等难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/18.jpg)
4+
5+
[3Sum](https://leetcode.windliang.cc/leetCode-15-3Sum.html)类似,只不过是找四个数,使得和为 target,并且不能有重复的序列。
6+
7+
如果之前没有做过[3Sum](https://leetcode.windliang.cc/leetCode-15-3Sum.html)可以先看看,自己再上边的基础上加了一个循环而已。
8+
9+
```java
10+
public List<List<Integer>> fourSum(int[] num, int target) {
11+
Arrays.sort(num);
12+
List<List<Integer>> res = new LinkedList<>();
13+
//多加了层循环
14+
for (int j = 0; j < num.length - 3; j++) {
15+
//防止重复的
16+
if (j == 0 || (j > 0 && num[j] != num[j - 1]))
17+
for (int i = j + 1; i < num.length - 2; i++) {
18+
//防止重复的,不再是 i == 0 ,因为 i 从 j + 1 开始
19+
if (i == j + 1 || num[i] != num[i - 1]) {
20+
int lo = i + 1, hi = num.length - 1, sum = target - num[j] - num[i];
21+
while (lo < hi) {
22+
if (num[lo] + num[hi] == sum) {
23+
res.add(Arrays.asList(num[j], num[i], num[lo], num[hi]));
24+
while (lo < hi && num[lo] == num[lo + 1])
25+
lo++;
26+
while (lo < hi && num[hi] == num[hi - 1])
27+
hi--;
28+
lo++;
29+
hi--;
30+
} else if (num[lo] + num[hi] < sum)
31+
lo++;
32+
else
33+
hi--;
34+
}
35+
}
36+
}
37+
}
38+
return res;
39+
}
40+
```
41+
42+
时间复杂度:O(n³)。
43+
44+
空间复杂度:O(N),最坏情况,即 N 是指 n 个元素的排列组合个数,即 $$N=C^4_n$$,用来保存结果。
45+
46+
#
47+
48+
完全是按照 3Sum 的思路写的,比较好理解。

0 commit comments

Comments
 (0)