leetcode

文章目录

leetcode

704. 二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
const n = nums.length
let l = 0,
r = n - 1
while( l <= r) {
const mid = Math.floor(l + (r - l) / 2) // 防止整型溢出 2^53 - 1
if (nums[mid] === target) {
return mid
}

if (nums[mid] > target) {
r = mid - 1
} else {
l = mid + 1
}
}
return -1
}
分享到:

评论完整模式加载中...如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理