美文网首页
1. 两数之和

1. 两数之和

作者: CN_HarrySun | 来源:发表于2018-11-21 16:15 被阅读6次

    题目详情:
    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的两个整数。
    你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

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

    import UIKit
    class Solution {
        func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            var dict = [Int: Int]()
            for (index, value) in nums.enumerated() {
                let complement = target - value // 目标值 = target - 当前值
                if let dictValue = dict[complement] { // 如果目标值在字典中有
                    return [dictValue, index] // 返回d目标值的index和当前值的index
                }
                dict[value] = index // 存储当前值的index(key:当前的值,下标)
            }
            return [0]
        }
    }
    
    let array = [2, 7, 11, 15]
    let solution = Solution()
    solution.twoSum(array, 9)
    
    

    相关文章

      网友评论

          本文标题:1. 两数之和

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