美文网首页
4、Two Sum(Easy)

4、Two Sum(Easy)

作者: 一念之见 | 来源:发表于2016-04-07 13:41 被阅读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
        }
    }
    

    相关文章

      网友评论

          本文标题:4、Two Sum(Easy)

          本文链接:https://www.haomeiwen.com/subject/gnbmlttx.html