4、Two Sum(Easy)

2016-04-07  本文已影响7人  一念之见

Problem Description

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Analyze

hash,check dictionary

Code

class Solution {
    func twoSum(nums: [Int], _ target: Int) -> [Int] {
        var mapping: [Int : Int] = [:]
        var result: [Int] = []
        
        for (index, num) in nums.enumerate() {
            mapping[num] = index
        }
        
        for (index, num) in nums.enumerate() {
        
            let gap = target - num
            
            if let i = mapping[gap] where i > index {
                result.appendContentsOf([index, i])
                break
            }
        }
        
        return result
    }
}
上一篇 下一篇

猜你喜欢

热点阅读