mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 第15题. 三数之和 Swift版本
This commit is contained in:
@ -434,6 +434,46 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
```swift
|
||||||
|
// 双指针法
|
||||||
|
func threeSum(_ nums: [Int]) -> [[Int]] {
|
||||||
|
var res = [[Int]]()
|
||||||
|
var sorted = nums
|
||||||
|
sorted.sort()
|
||||||
|
for i in 0 ..< sorted.count {
|
||||||
|
if sorted[i] > 0 {
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
if i > 0 && sorted[i] == sorted[i - 1] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var left = i + 1
|
||||||
|
var right = sorted.count - 1
|
||||||
|
while left < right {
|
||||||
|
let sum = sorted[i] + sorted[left] + sorted[right]
|
||||||
|
if sum < 0 {
|
||||||
|
left += 1
|
||||||
|
} else if sum > 0 {
|
||||||
|
right -= 1
|
||||||
|
} else {
|
||||||
|
res.append([sorted[i], sorted[left], sorted[right]])
|
||||||
|
|
||||||
|
while left < right && sorted[left] == sorted[left + 1] {
|
||||||
|
left += 1
|
||||||
|
}
|
||||||
|
while left < right && sorted[right] == sorted[right - 1] {
|
||||||
|
right -= 1
|
||||||
|
}
|
||||||
|
|
||||||
|
left += 1
|
||||||
|
right -= 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
Reference in New Issue
Block a user