查找数组中第一个大于/大于等于的元素下标

这个问题应该肯定使用二分查找,时间复杂度是O(logn)。比较麻烦的一点在于如何当前这个数是不是第一个大于等于这个数的下标,需要我们用 res 来存放最近的满足条件的那个数,这样left或者right变化就不怕了。也可以直接借助标准库中的 lower_bound 和 upper_bound() ,详细见https://blog.csdn.net/qq_40160605/article/details/80150252

#include<iostream>
#include<vector>
using namespace std;

//查找nums中第一个大于target的数字的下标,没有则返回-1
int search_firstL_index(vector<int> &nums,int target)
{
    int left = 0, right = nums.size() - 1, res = right;
    while(left <= right)
    {
        int mid = left + (right - left) / 2 ;
        if(nums[mid] > target)
        {
            res = mid; right = mid - 1;
        }else
        {
            left = mid + 1;
        }

    }
    if(target<nums[res]) return res;
    return -1;
}
//查找nums中第一个大于等于target的数字的下标,没有则返回-1
int search_firstLE_index(vector<int> &nums,int target)
{
    int left = 0, right = nums.size() - 1, res = right;
    while(left <= right)
    {
        int mid = left + (right - left) / 2 ;
        if(nums[mid] >= target)
        {
            res = mid; right = mid - 1;
        }else
        {
            left = mid + 1;
        }

    }
    if(target<=nums[res]) return res;
    return -1;
}

int main()
{
    vector<int> nums = {1,3,5,7,9,10,18,20,30,50,60,70};
    //测试大于功能
    // cout<<search_firstL_index(nums,-5)<<" ";
    // cout<<search_firstL_index(nums,1)<<" ";
    // cout<<search_firstL_index(nums,7)<<" ";
    // cout<<search_firstL_index(nums,16)<<" ";
    // cout<<search_firstL_index(nums,70)<<" ";
    // cout<<search_firstL_index(nums,90)<<" ";
    // 测试大于等于功能
    // cout<<search_firstLE_index(nums,-9)<<" ";
    // cout<<search_firstLE_index(nums,7)<<" ";
    // cout<<search_firstLE_index(nums,16)<<" ";
    // cout<<search_firstLE_index(nums,60)<<" ";
    // cout<<search_firstLE_index(nums,70)<<" ";
    // cout<<search_firstLE_index(nums,80)<<" ";
    return 0;
}

 

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值