LeetCode (1) - Swift 两数之和

340 阅读1分钟

题目:两数之和

描述:

给定一个整数数列,找出其中和为特定值的那两个数。

你可以假设每个输入都只会有一种答案,同样的元素不能被重用。

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

时间复杂度对O(n^2)

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    for i in 0 ..< nums.count {
        for j in i + 1 ..< nums.count {
             let result = nums[i] + nums[j]
            if result == target {
               return [i , j]
            }
        }
    }
    return [-1 ,-1]
}

twoSum([2, 7, 11, 15], 9)

时间复杂度O(n)

func twoSum2(_ nums: [Int], _ target: Int) -> [Int] {
    var numerIndexDic = [Int:Int]()
    for (index, num) in nums.enumerated() {
        guard let pairedIndex = numerIndexDic[target - num] else {
            numerIndexDic[num]  = index
            continue
        }
        return [pairedIndex,index]
    }
    return[-1 ,-1]

}

twoSum2([2, 7, 11, 15], 9)