1、原题
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
2、思路
3、代码
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// 需要用到字典,先声明初始化一个字典
var dict = [Int: Int]()
// 遍历整个数组
for i in 0..<nums.count {
// 得到当前元素的另一个与之对应的元素
let another = target - nums[i]
// 判断这个another是否在新字典中,因为后面会存之前生成的another
if dict.keys.contains(another) {
// 如果字典中包含,就找到了,返回当前元素的索引和another的
return [i, dict[another]!]
}
dict[nums[i]] = i
}
return []
}
}
网友评论