// 1. 给一个整型数组和一个目标值,判断数组中是否有两个数字之和等于目标值
func twoSum(nums: [Int], _ target: Int) -> Bool {
// 集合: 用来存放遍历过的数组中的值
var set = Set<Int>()
// 遍历数组
for num in nums {
// 目标值 - 当前遍历的值, 检查集合中是否有该值, 如果有, 证明存在
if set.contains(target - num) {
return true
}
// 如果没有, 则将该值放入集合
set.insert(num)
}
// 全部遍历完都没有找到的话, 证明不存在, 返回false
return false
}
print(twoSum(nums: [1, 2, 3, 4, 5], 10));
// 2. 给定一个整型数组中有且仅有两个数字之和等于目标值,求两个数字在数组中的序号
func twoSum2(nums: [Int], _ target: Int) -> [Int] {
// 字典: 用来存储遍历过的数组中的值和下标
var dic = [Int:Int]()
// 遍历数组
for (i, num) in nums.enumerated() {
// 目标值 - 当前遍历的值, 检查字典中是否有该值, 如果有, 则返回两数下标
if let lastIndex = dic[target - num] {
return [lastIndex, i]
// 如果没有, 则向字典中存入数据
} else {
dic[num] = i
}
}
// 如果遍历完都没有查到, 则返回空数组
return []
}
print(twoSum2(nums: [1, 2, 3, 4, 5], 10))