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

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • Two Sum Question: Given an array of integers, return indi...
    Kay_Coding阅读 437评论 0 0
  • 惶惶然已经大二了。与你们散落在不同的地方,各自不同的在努力开拓。怀疑,深省,疑问不停的在内心出现、徘徊。最初的时候...
    青荷白茶阅读 286评论 0 3
  • 前段时间看《笑傲江湖》,小说的感觉还是比影视作品更深刻些。忍不住提笔记录触动我的点点细节。 看到吸星大法时,深有感...
    sun2016阅读 345评论 0 1
  • 13年下半年,感觉自己的身体,精神状态每况愈下。上班时,对于琐碎而复杂的工作内容匆匆忙忙塞责了事。下班后,要么开启...
    猫儿刺阅读 228评论 2 0