LeetCode Binary Search All In One_binary searchLeetCode Binary Search All In One LeetCode Binary Search Best Solutions in JavaScript Binary Search 二分查找算法



LeetCode Binary Search All In One

Binary Search

LeetCode Binary Search All In One_binary search

二分查找算法

 

复杂度分析

时间复杂度:\mathcal{O}(\log N)O(logN)。

空间复杂度:\mathcal{O}(1)O(1)。

LeetCode Binary Search Best Solutions in JavaScript

  1. 位运算

/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
const search = (nums, target) => {
if(nums.length === 0){
return -1;
}
let lo = 0;
let hi = nums.length - 1;
while(lo <= hi){
// 位运算 12 >> 1 === 6 ✅
const mid = lo + ((hi - lo) >> 1);
if(nums[mid] === target){
return mid;
}else if(nums[mid] < target){
lo = mid + 1;
}else{
hi = mid - 1;
}
}
return -1;
};


  1. 经典双指针
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let left = 0;
let right = nums.length-1
let middle
while(right >= left){
middle = Math.floor((left+right)/2)
const midval = nums[middle]
if(midval === target) return middle;
else if(midval > target) right = middle-1;
else left = middle +1;
}
return -1
};


bad

/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
const findValue = (arr, target) => {
let result = -1;
let len = arr.length;
let index = Math.floor(len / 2);
let mid = arr[index];
let leftArr = arr.slice(0, index)
let rightArr = arr.slice(index + 1, len)
if(mid === target) {
result = nums.indexOf(mid);
} else {
if(mid > target) {
// left
result = findValue(leftArr, target)
}
if(mid < target) {
// right
result = findValue(rightArr, target)
}
}
return result;
}
return findValue(nums, target);
};