方法1:2层for循环暴力破解
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>02.leetcode2数之和</title>
</head>
<body>
<script>
var nums = [2, 7, 11, 15]
var target = 9
var arr=[]
var twoSum = function () {
for(var i=0;i<nums.length;i++){
for(var j=i+1;j<nums.length;j++){
if(target==nums[i]+nums[j]){
arr.push(i)
arr.push(j)
console.log(arr)
return
}
}
}
};
twoSum()
</script>
</body>
</html>
方法2利用ES6中的Map数据结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>02.leetcode2数之和</title>
</head>
<body>
<script>
var nums = [2, 11, 7, 15]
var target = 9
var twoSum = function () {
const map = new Map();
for (var i = 0; i < nums.length; i++) {
x = target - nums[i]
if (map.has(x)) {
console.log([map.get(x), i])
return
}
map.set(nums[i], i)
}
};
twoSum()
</script>
</body>
</html>