哈希
解题思路
迭代 nums 并将 <nums[i], inx> 放入 hash 中;
放入之前,会对其寻找
targte - nums[i]是否已经存在于 hash 表中;
- 不存在直接将 nums[i] 放入 hash;
- 存在则直接获取索引,直接返回即可;
复杂度
-
时间复杂度:
O(N),其中 N 是数组中的元素数量;对于每一个元素 x 我们可以O(1)地寻找target - x; -
空间复杂度:
O(N);
代码实现
var twoSum = function (nums, target) {
const hash = new Map();
for (let i = 0; i < nums.length; i++) {
if (hash.has(target - nums[i])) {
return [i, hash.get(target - nums[i])];
}
hash.set(nums[i], i);
}
};
参考资料
算法基础🔮 优先级队列
上一篇