You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (i !== j && nums[i] + nums[j] === target) {
return [i, j]
}
}
}
}
2、一趟哈希表
var twoSum = function(nums, target) {
const map = {}
for (let i = 0; i < nums.length; i++) {
const n = nums[i]
if (target - n in map) {
return [map[target - n], i]
} else {
map[n] = i
}
}
}
在给哈希表添加元素的同时寻找有没有符合目标的答案,如果有就直接返回,没有就继续构造哈希表。
时间复杂度O(n), 空间复杂度O(n)
The text was updated successfully, but these errors were encountered:
答案:
1、暴力破解法
2、一趟哈希表
The text was updated successfully, but these errors were encountered: