算法学习100天——2 二分查找

二分查找:

  1. 有序数组,查找指定数
class solution{
    public int binarySearch(int[] nums, int target){
        int left = 0;
        int right = nums.legth;
        while (left <= right){
            // 当前数组范围内的中点
            int mid = left + ((right - left) >> 1);
            if(nums[mid] < target){
                left = mid + 1;
            }else if(nums[mid] > target){
                right = mid - 1;
            }else {
              return mid;  
            }
        }
        // 没找到
        return -1;
    }
}
  1. 有序数组,查找左右边界问题
class solution{
    /**
 	* 找左边界
 	*/
	public int leftBound(int[] nums, int target){
		// 左边界
        int left = 0;
        int right = nums.length - 1;
        while(left < right){
            int mid = left + ((right - left) >> 1);
            if(nums[mid] >= target){
                right = mid;
            }else{
                left = mid + 1;
            }
        }
        // 不存在左边界
        if(nums.length == 0 || nums[left] != target){
            return -1;
        }
    }
    
    /**
     * 找右边界
     */
	public int rightBound(int[] nums, int target){
        int left = 0;
        int right = nums.length;
        while(left < right){
            // 这里的mid要加一再除以2,因为是求右边界,要保证中间值向右偏移
            int mid = left + ((right - left + 1) >> 1);
            if(nums[mid] <= target){
                left = mid;
            }else{
                right = mid - 1;
            }
        }
        // 不存在右边界
        if(nums.length == 0 || nums[right] != target){
            return -1;
        }
    }
}
posted @ 2022-02-26 23:16  浪漫主义程序员  阅读(24)  评论(0编辑  收藏  举报