【内功】基础算法——二分查找

1. 自己实现 lower_bound, upper_bound

复制代码
 1 int my_lower_bound(vector<int> nums, int target) {
 2     int left = 0, right = nums.size();
 3     while (left < right) {
 4         long long mid = left + (right - left) / 2;
 5         if ((nums[mid] < target) {
 6             left = mid + 1;
 7         } else {
 8             right = mid;
 9         }
10     }
11     return left;
12 }
复制代码

 

复制代码
 1 int my_upper_bound(vector<int> nums, int target) {
 2     int left = 0, right = nums.size();
 3     while (left < right) {
 4         long long mid = left + (right - left) / 2;
 5         if ((nums[mid] > target) {
 6             right = mid;
 7         } else {
 8             left = mid + 1;
 9         }
10     }
11     return left;
12 }
复制代码

 

posted @   zhangwanying  阅读(241)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示