单纯记录一下自己要刷题的日子 2022年5月10号 目前凌晨12:14
<!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>
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有