4、Two Sum(Easy)

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
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 有封面吗?
    神秘世界阅读 213评论 0 0
  • 以前一直后悔母亲在世时没带她出去好好玩玩,总以为天天日出开作,日落后息的母亲不可能会一下离开我们的。可到了想带她出...
    A寒秋阅读 431评论 6 11
  • (一)下午,坐着坐着走神了,走神的时候最接近你…… 晚上,中秋。小男孩兴奋地指着天空某处对小女孩说:“快看——,那...
    笑笑_小夕阅读 993评论 0 0
  • 那首《贝加尔湖》让我们邂逅了一场说走就走的旅行。 那里绿草如茵,湖面平静,杉树成林。
    SusanLee_794d阅读 350评论 0 0