二分查找

题解:https://juejin.cn/post/6926819139478618120#heading-2

力扣:https://leetcode.cn/problems/two-sum/submissions/

题目

在给定数组中找到 2 个数之和等于给定值的数字,结果返回 2 个数字在数组中的下标。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const arrMap = new Map()
for(i=0;i<nums.length;i++){
otherNum =target -nums[i]
if(arrMap.has(otherNum)){
return [arrMap.get(otherNum),i]
}
arrMap.set(nums[i],i)
}
return null
};