Two Sum

作者: 咸鱼灬_ | 来源:发表于2019-06-22 10:42 被阅读0次

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 exactly one 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].

1、直接循环

/**
 * Question Link: https://leetcode.com/problems/two-sum/
 * Primary idea: Loop through each element x and find if there is another value that equals to target - x.
 *
 * Time Complexity: O(n^2), Space Complexity: O(1)
 */

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    for i in 0..<nums.count {
        for j in 0..<nums.count {
            if nums[j]  == target - nums[i] {
                return [i ,j]
            }
        }
    }
    fatalError("No valid outputs")
}

2、对数组迭代时用哈希表来记录迭代过的数据,每次迭代都可通过哈希表快速查找结果

/**
 * Question Link: https://leetcode.com/problems/two-sum/
 * Primary idea: Traverse the array and store target - nums[i] in a dict
 *
 * Time Complexity: O(n), Space Complexity: O(n)
 */
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        //nums的值为key,索引为value
        var dict = [Int: Int]()
       
        for (i, num) in nums.enumerated() {
             //每次迭代,通过dict[target - num]快速查询
            if let lastIndex = dict[target - num] {
                //如果有结果,则表示nums[i] + nums[lastIndex] = target  
                return [lastIndex, i]
            }
            dict[num] = i
        }
        fatalError("No valid outputs")
    }

相关文章

网友评论

      本文标题:Two Sum

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