给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
/*
把数组的值作为字典的key,数组下标最为字典的value
*/
var dict = Dictionary<Int,Int>()
var i = 0;
for n in nums {
dict[n] = i;
i = i+1;
}
var arr = [-1,-1]
var j = 0;
for n in nums {
/**
判断条件 字典中存在 target-n的值m,并且这个值不是当前的n,这要根据坐标来判断
**/
if dict.keys.contains(target - n) && j != dict[target-n] {
arr[0]=j;
arr[1]=dict[target-n] ?? -1
return arr
}
j=j+1;
}
return arr;
}
/*
第二种方法 两次遍历。比较暴力,第一种方法效率更高
**/
func twoSum2(_ nums:[Int],_ target:Int) -> [Int] {
var i:Int = 0
for n in nums {
var j:Int = 0
for k in nums {
let sum = n+k
if sum == target && i != j {
return[i,j]
}
j=j+1
}
i=i+1
}
return []
}