mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
0001.两数之和:简化Swift实现
This commit is contained in:
@ -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 []
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user