給一個包含integer的數組,若是數組中兩個數的和爲給的目標數,則返回這兩個數的索引,你能夠假設每次輸入有一個解決方案,而且你不會兩次使用同一個值。
(Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.)數組
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var result = [Int]()
for i in 0 ..< nums.count {
for j in (i + 1) ..< nums.count {
if nums[i] + nums[j] == target {
result = [i, j]
}
}
}
return result
}複製代碼
def twoSum(self, nums, target):
dict = {}
for i in range(len(nums)):
x = nums[i]
if target - x in dict:
return (dict[target - x], i)
dict[x] = i複製代碼