二分搜索算法模板

2023-12-29 10:28:58

二分搜索算法模板

1.最基本的二分搜索算法

int binary_search(int[] nums,int target){
	int left = 0,right = nums.length - 1;
	while(left <= right){
		int mid = left + (right - left)/2;
        if(nums[mid] < target){
             left = mid + 1;
         }else if(nums[mid] > targrt){
              right = mid - 1;
         }else if(nums[mid] == target){
          //直接返回
              return mid;
         }
    }
    //直接返回
    return -1;
}

2.寻找左侧边界的二分搜索算法

int left_bound(int[] nums,int target){
    int left = 0,right = nums.length - 1;
    while(left <= right){
        int mid = left + (right - left)/2;
        if(nums[mid] < target){
            left = mid + 1;
        }else if(nums[mid] > target){
            right = mid - 1;
        }else if(nums[mid] == target){
            // 收缩右边界,锁定左侧边界
            right = mid - 1;
        }
        // 检查left越界的情况
        if(left >= nums.length || nums[left] != target){
            return -1;
        }
        return left;
    }
}

3.寻找右边界的二分搜索算法

int right_bound(int[] nums,int target){
    int left = 0,right = nums.length - 1;
    while(left <= right){
        int mid = left + (right - left)/2;
        if(nums[mid] < target){
            left = mid + 1;
        }else if(nums[mid] > target){
            right = mid - 1;
        }else if(nums[mid] == target){
            // 收缩左边界,锁定右侧边界
            left = mid + 1;
        }
    }
     // 检查right越界的情况
    if(right < 0 || nums[right] != target){
        return -1;
    }
    return right;
}

文章来源:https://blog.csdn.net/weixin_42031847/article/details/124872185
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。