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