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 exactlyone 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

因为nums[0] + nums[1] = 2 + 7 = 9

所以返回 return [0,1]

 

下面用swift语言编写,可以直接运行出来

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        twoSum([1,3,6], 4)
        let num:[Int] = [1,2,4,6,7]
        let target = 11
        var someArray4=[Int]()
        someArray4 = twoSum(num, target)
        print(someArray4)
        
    }
    
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        
        var dic:[Int:Int] = [Int:Int]()
        
        for i in 0..<nums.count {
            let result = target - nums[i]
            if let key = dic[result]{
                return [i,key]
            }
            dic[nums[i]] = i
        }
        return [0]
    }


}

 

posted @ 2018-12-20 11:07  国孩  阅读(224)  评论(0编辑  收藏  举报