题目简介
给一个包含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.)
Swift (Swift version 3.1)
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
}Python (Version 3.5)
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