C++实现二分、lower_bound 和 upper_bound

二分

// Return the position of an element in sorted array "A" of
// size "n" with value "K". If "K" is not in "A", return
// the value "n".
int binary(int A[], int n, int K) {
        int l = -1;
        int r = n; // l and r are beyond array bounds
        while (l+1 != r) { // Stop when l and r meet
                int i = (l+r)/2; // Check middle of remaining subarray
                if (K < A[i]) r = i; // In left half
                if (K == A[i]) return i; // Found it
                if (K > A[i]) l = i; // In right half
        }
        return n; // Search value not in A
}

lower_bound 和 upper_bound

lower_bound 返回数组中第一个不小于目标值的元素的iterator,(第一个>=target的数)

upper_bound 返回数组中第一个大于目标值的元素的iterator, (第一个>target的数)

在这里插入图片描述

int my_low_boundint(vector<int>& nums, int target) {
    // 找到比n大于或等于的第一个元素
    int l = 0, r = nums.size(), mid; // r = n的设计是为了
    while (l < r) {
        mid = l + ((r - l) >> 1); // 防止溢出的设计, 移位更快
        if (nums[mid] < target) {
            // 小于的时候向右移动,直到移动到大于等于target就不变了
            l = mid + 1;
        } else {
            // 直至移动到和l相同的地方
            r = mid;
        }
    }
    return l;
} 
int my_up_bound(vector<int> index , int n){
    // 找到比n大的第一个元素
    int l = 0,r = index.size(),mid;
    while(l<r){
        mid = l + ((r - l) >> 1); // 防止溢出的设计, 移位更快
        if(index[mid] <= n) l = mid +1; // 小于的时候向右移动,直到移动到大于target就不变了
        else r = mid; // 比n大就一直向左边移动
    }
    return l;
}

c++ STL 版使用

c++ STLupper_boundlower_bound
头文件 #include<algorithm>
函数功能:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。
函数功能:函数upper_bound在first和last中的前闭后开区间进行二分查找,返回大于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>

using namespace std;
 
int main()
{
    int array[5] = {1 , 2 , 2 , 3 , 5 };
    int t1 = upper_bound( array , array+5 , 2 )-array;
    //t1 = 3 ; array[t1] = 3;
    int t2 = lower_bound( array , array+5 , 2 )-array;
    //t2 = 1 ; array[t2] = 2;
    return 0;
}

例题 34. 在排序数组中查找元素的第一个和最后一个位置

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AlwaysDayOne

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值