每日一题 — 二分查找

时间:2024-04-23 07:29:56

704. 二分查找 - 力扣(LeetCode)

 

朴素二分查找模板:

while(.......){
            //防止溢出
            int mid = left+(right - left)/2;
            if(........){
                right = mid-1;
            }else if(......){
                left = mid+1;
            }else{
                return mid;
            }
        }

 代码:

    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while(left <= right){
            //防止溢出
            int mid = left+(right - left)/2;
            if(nums[mid] > target){
                right = mid-1;
            }else if(nums[mid] < target){
                left = mid+1;
            }else{
                return mid;
            }
        }
        return -1;
    }