【EASY】Two Sum

发布于: 2018-12-06 23:41
阅读: 11
评论: 0
喜欢: 0

问题

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

分析过程

  • 输入:nums = [2, 7, 11, 15], target = 9
  • 输出:[0, 1]
  • 思路:遍历数组,用数组的元素做 key,索引做 value 存入字典。遍历时寻找字典里有没有以 target - key 的元素,如果有的话取出下标返回即可。

解决方法

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var dict = [Int: Int]()
    
    for (i, num) in nums.enumerated() {
        dict[num] = i
        if let j = dict[target - num] {
            return [j, i]
        }
    }
    
    fatalError("No valid outputs")
}

let nums = [2, 7, 11, 15]
let target = 17
print(twoSum(nums, target))

Thanks for reading.

All the best wishes for you! 💕