From 3078fb8eeaaa0a7e4200e6a0c2eb5e7835ea5bb4 Mon Sep 17 00:00:00 2001 From: bqlin Date: Sun, 19 Dec 2021 17:22:04 +0800 Subject: [PATCH] =?UTF-8?q?0001.=E4=B8=A4=E6=95=B0=E4=B9=8B=E5=92=8C?= =?UTF-8?q?=EF=BC=9A=E7=AE=80=E5=8C=96Swift=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 37c95736..8551274c 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -207,18 +207,16 @@ function twoSum(array $nums, int $target): array Swift: ```swift func twoSum(_ nums: [Int], _ target: Int) -> [Int] { - var res = [Int]() - var dict = [Int : Int]() - for i in 0 ..< nums.count { - let other = target - nums[i] - if dict.keys.contains(other) { - res.append(i) - res.append(dict[other]!) - return res + // 值: 下标 + var map = [Int: Int]() + for (i, e) in nums.enumerated() { + if let v = map[target - e] { + return [v, i] + } else { + map[e] = i } - dict[nums[i]] = i } - return res + return [] } ```