要求 : 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,并返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重復利用這個數組中同樣的元素。
一, 可以暴力解題, 即兩次for循環即可求出
二, 使用字典一次遍歷, 效率最高, 代碼如下
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dic = [Int: Int]()
for (index , n) in nums.enumerated() {
if dic.keys.contains(target-n) , index != dic[target-n] {
return [index, dic[target-n]!]
}
dic[n] = index
}
return []?
}
}
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum