0001.两数之和:简化Swift实现

This commit is contained in:
bqlin
2021-12-19 17:22:04 +08:00
parent 59b38a9ebf
commit 3078fb8eea

View File

@ -207,18 +207,16 @@ function twoSum(array $nums, int $target): array
Swift Swift
```swift ```swift
func twoSum(_ nums: [Int], _ target: Int) -> [Int] { func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var res = [Int]() // 值: 下标
var dict = [Int : Int]() var map = [Int: Int]()
for i in 0 ..< nums.count { for (i, e) in nums.enumerated() {
let other = target - nums[i] if let v = map[target - e] {
if dict.keys.contains(other) { return [v, i]
res.append(i) } else {
res.append(dict[other]!) map[e] = i
return res
} }
dict[nums[i]] = i
} }
return res return []
} }
``` ```