LeetCode 1. 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

自己的解法:思路2层for循环遍历数组,判断2数之和是否为目标值,是则返回,不是继续循环,时间复杂度n^2
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        for i in 0..<nums.count{
            for j in i+1..<nums.count{
                if nums[i] + nums[j] == target{
                    return [i,j]
                }
            }
        }
        return []
 }
查看他人的解法:用一个map来存已经遍历过的数,用目标数-当前遍历的值来计算需要的值,再判断map中是否存在该值,有则返回结果,没有将当前值存入map中,继续遍历,时间复杂度n
 func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        
        /// Make a Hash Table of [NumberInInput: IndexOfNumber]
        var map: [Int: Int] = [:]
        // Loop through nums
        for (index, value) in nums.enumerated() {
            
            /// Calculate the number that would be needed
            /// to match the target
            let complement = target - value
            /// Check if the complement exists in the table
            if let pair = map[complement] {
                return [pair, index]
            }
            
            /// Add the complement to the table
            map[nums[index]] = index
        }
        return []

}
学到的知识点

enumerated()
可用于快速遍历,(index,value)中,index表示数组的索引,value表示值,而且这个index其实是offset,看下面的例子。

let array = ["a", "b", "c", "d", "e"]
let arraySlice = array[2..<5]
arraySlice[2] // => "c"
arraySlice.enumerated().first // => (0, "c")
arraySlice[0] // fatalError

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

推荐阅读更多精彩内容

  • leetcode 1. 两数之和题目: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每...
    和尚我不念经阅读 409评论 0 0
  • <center>#1 Two Sum</center> link Description:Given an arr...
    铛铛铛clark阅读 2,213评论 0 3
  • 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被...
    WindMajor阅读 235评论 0 0
  • 前言 从今天开始,将会开启我的 LeetCode 打卡之路。为了能让打卡坚持下去,就给自己设定了用博客来记录打卡过...
    DonLex阅读 145评论 0 0
  • 朱自清说“洗手的时候,日子从水盆里过去,吃饭的时候,日子从饭碗里过去,默默时,日子便从凝然的双眼过去......”...
    Dear半封情书阅读 4,344评论 0 2