From 995aa86ab2eb21559bcdd0d3cc91e486e33cade1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Wed, 8 Sep 2021 13:28:04 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E7=AC=AC18=E9=A2=98.=20?= =?UTF-8?q?=E5=9B=9B=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/0018.四数之和.md | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index c81c5df7..9891f0fe 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -354,6 +354,54 @@ class Solution { } ``` +Swift: +```swift +func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] { + var res = [[Int]]() + var sorted = nums + sorted.sort() + for k in 0 ..< sorted.count { + // 这种剪枝不行,target可能是负数 +// if sorted[k] > target { +// return res +// } + // 去重 + if k > 0 && sorted[k] == sorted[k - 1] { + continue + } + + let target2 = target - sorted[k] + for i in (k + 1) ..< sorted.count { + if i > (k + 1) && 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 < target2 { + left += 1 + } else if sum > target2 { + right -= 1 + } else { + res.append([sorted[k], 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) * B站视频:[代码随想录](https://space.bilibili.com/525438321)