1-5年Java工程师107道必不可少的面
584 2023-04-03 03:31:37
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
输入:nums = [2,7,11,15], target = 9输出:[0,1]解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
链接:leetcode-cn.com/problems/tw…
解析
func twoSumTest(_ nums: [Int], _ target: Int) -> [Int] { var dic: [Int : Int] = [:] //创建字典 for (index,item) in nums.enumerated() { let math = target - item //判断是否包含key,想要的是 if(dic.keys.contains(math)) { if let mathIndex = dic[math] , mathIndex != index { return [mathIndex , index] //实际上这里的index+1,所以这里的话index 永远大于mathindex } } //第一次遍历时,字典是没有数据的,运行到此位置才给字典添加数据 //这也是为什么要return[~,index] 能做到的原因 dic[item] = index } return []}//打印print(twoSumTest([13,2,2,3,4,8], 4))
总结: