【HOT100】1-两数之和
链接直达:1-两数之和
分析:
梦(maybe噩梦)开始的地方!
这个题在哈希,应该是将数组和下标存储在unordered_map中,使用hash的find(),
常规想法可能是先创建unordered_map,然后再遍历数组,使用find(),
但是呢,我们可以一边遍历,一边查找,没找到再插入{nums[i],i}
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numToIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
int complement = target - num;
// 检查目标差值是否已在哈希表中
if (numToIndex.containsKey(complement)) {
return new int[]{i, numToIndex.get(complement)};
}
// 存储当前数字和其索引(先查后存,避免重复使用同一元素)
numToIndex.put(num, i);
}
return new int[]{};
}
}
题解欣赏环节:
看了一遍访问量高的,没啥骚操作,所以这题收获就是一遍哈希
复杂度分析
时间复杂度:O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以 O(1) 地寻找 target - x。
空间复杂度:O(N),其中 N 是数组中的元素数量。主要为哈希表的开销。

浙公网安备 33010602011771号