15. 三数之和

单纯三层遍历会超时卡在最后三个测试用例,参考题解解法。

执行用时:116 ms, 在所有 Swift 提交中击败了99.44%的用户
内存消耗:17.1 MB, 在所有 Swift 提交中击败了100.00%的用户

题目链接:https://leetcode-cn.com/problems/3sum/

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
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
var sortnums = nums.sorted()
let n = sortnums.count
var first = 0, second = 0, third = 0
var res = [[Int]]()
for first in 0 ..< n {
if first > 0 && sortnums[first] == sortnums[first-1] {
continue
}
third = n - 1
second = first + 1
for second in second ..< n {
if second > first + 1 && sortnums[second] == sortnums[second-1] {
continue
}
while second < third && sortnums[first] + sortnums[second] + sortnums[third] > 0 {
third -= 1
}
// 指针重合说明下一轮循环找不到更小的c使得a+b+c=0
if second == third {
break
}
if sortnums[first] + sortnums[second] + sortnums[third] == 0 {
res.append([sortnums[first], sortnums[second], sortnums[third]])
}
}
}
return res
}
}

15. 三数之和
https://pisces34.github.io/2021/10/10/leetcode/15/
发布于
2021年10月10日
许可协议