【EASY】Two Sum

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

问题

原题链接:https://leetcode.com/problems/two-sum/

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 的元素,如果有的话取出下标返回即可。

解决方法

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

Thanks for reading.

All the best wishes for you! 💕