From 3db7b5290d12f91124bfc13668b7a2cbbec6bfe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Mon, 6 Sep 2021 23:06:37 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E7=AC=AC15=E9=A2=98.=20?= =?UTF-8?q?=E4=B8=89=E6=95=B0=E4=B9=8B=E5=92=8C=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index adb9a113..6b5311ae 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -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)