单纯记录一下自己要刷题的日子 2022年5月10号 目前凌晨12:14
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
输入:nums = [2,7,1,15], target = 9
输出:[0,1]
</body>
<script>
let nums = [2, 7, 0, 3, 4]
let target = 9
// 1:使用map 解
var oneSum = function(nums, target) {
const map = new Map()
for (let i = 0; i < nums.length; i ) {
const otherIndex = map.get(target - nums[i])
if (otherIndex !== undefined) {
//能匹配到返回当前map 中的value,及其当前的下标
return [otherIndex, i]
}
//先存起来
map.set(nums[i], i)
}
};
console.log("1:使用map 解", oneSum(nums, target))
// 2:直接for 循环匹配差值
var twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i ) {
let num = target - nums[i]
let res1 = i
let res2 = nums.indexOf(num, i 1);
if (res2 !== -1) {
return [res1, res2]
}
}
};
console.log("2.直接for 循环匹配差值", twoSum(nums, target))
// 3:直接for 循环
var threeSum = function(nums, target) {
for (let i = 0, len = nums.length; i < len - 1; i ) {
for (let j = i 1; j < len; j ) {
if (nums[i] nums[j] == target) {
return [i, j]
}
}
}
};
console.log("3:直接for 循环", threeSum(nums, target))
// 4:map 哈希
var fourSum = function(nums, target) {
const map = new Map()
for(let i = 0; i < nums.length; i ) {
const d = target - nums[i]
if(map.has(d)) {
return [map.get(d), i]
}
map.set(nums[i], i)
}
};
console.log("4:map 哈希", fourSum(nums, target))
</script>
</html>