在一个有序的数组中,查找小于某个数的个数
[1, 2, 3, 4]
2
// 1
二分查找
let searchInsert = function (arr, x) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = (left + right) >> 1;
if (arr[mid] === x) {
return mid;
} else if (x < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
}
let arr = [1, 2, 3]
console.log(searchInsert(arr, 2))
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!