阅读 49

二分查找

定义

  • 当我们要从一个序列中查找一个元素的时候,二分查找是一种非常快速的查找算法,二分查找又叫折半查找。它对要查找的序列有两个要求,一是该序列必须是有序的。

代码实现

let search = (nums, target) => {
    let left = 0;
    let right = nums.length;
    
    while(left < right){
        // 计算中间位置,实际相当于 Math.floor((left + right) / 2);
        let mid = (left + right) >>> 1;
        
        if(nums[mid] == target){
            return mid;
        }else if(nums[mid] > target){
            right = mid;
        } else if(nums[mid] < target){
            left = mid - 1;
        }
    }
    
    // 说明没有找到
    rerurn -1;
}
复制代码

应用

要求:给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。如果数组中不存在目标值 target,返回 [-1, -1]。

  • 代码实现
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target) {
    let left = 0;
    let right = nums.length;
    
    while(left < right){
        let mid = (left + right) >>> 1;

        if(nums[mid] > target){
            right = mid;
        } else if(nums[mid] < target){
            left = mid + 1;
        } else if(nums[mid] == target){
            right = mid
        }
    }

    let rightIndex = -1, leftIndex = -1;
    if(left == nums.length) return [-1, -1]
    else leftIndex = nums[left] == target ? left : -1;

    left = 0; right = nums.length;
    while(left < right){
        let mid = (left + right) >>> 1;

        if(nums[mid] > target){
            right = mid;
        } else if(nums[mid] < target){
            left = mid + 1;
        } else if(nums[mid] == target){
            left = mid + 1;
        }
    }

    if(left == 0) return [-1, -1]
    else rightIndex = nums[left - 1] == target ? left -1 : -1;

    return [leftIndex, rightIndex];
};
复制代码
文章分类
前端
文章标签