判断数组中是否存在两数之和等于目标值
show the code 代码展示
/*
* 给定一个整数数组和一个目标值, 判断数组中是否有两个数之和等于目标值.
*/
private func twoSum(nums: [Int], _ target: Int) -> Bool {
var set = Set<Int>();
for item in nums {
if set.contains(target - item) {
return true
}
set.insert(item);
}
return false
}
analysis 分析
- 采用集合可以优化查询的时间复杂度, 因为
set.contains
的时间复杂度为O(1), 本质原因是Set会通过元素的哈希值来查询是否存在; - 平均时间复杂度等于最坏情况时间复杂度: O(n)