Swift LeetCode 两数之和

209 阅读1分钟

首先想到的是利用字典的特性去处理这个问题

1,把value当key,下标是value

2,通过targat-value可以从字典中查找,查找不到就存入字典

3,查找到结果就返回

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {

var dict = Dictionary<Int,Int>()
for (index, value) in nums.enumerated() {
    let newValue = target-value
    let newindex = dict[newValue]
    if newindex == nil {
     dict[value] = index
   }else{
     let result = newindex
     return [result, index]
  }
}
return [-1,-1]   

}