leetcode 二分查找应用

34. Find First and Last Position of Element in Sorted Array

代码:

cpp 复制代码
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int low = lowwer_bound(nums,target);
        int high = upper_bound(nums,target);

        if(low == high)
            return {-1,-1};

        return {low,high-1};
    }
    int lowwer_bound(vector<int>& nums,int target)
    {
        int left = 0;
        int right = nums.size();
        int mid = 0;
        while(left < right){
            mid = left + ((right-left)>>1);
            if(nums[mid]>=target){
                right = mid;
            }else{
                left = mid + 1;
            }
        }
        return left;
    }
    int upper_bound(vector<int>& nums,int target){
        int left = 0;
        int right = nums.size();
        int mid = 0;
        while(left < right){
            mid = left + ((right - left)>>1);
            if(nums[mid]>target){
                right = mid;
            }else{
                left = mid +1;
            }
        }
        return left;
    }
};
相关推荐
phltxy2 小时前
C语言操作符详解
java·c语言·算法
aqiu1111112 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye3 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考4 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾4 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研5 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a187927218316 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_962297486 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye7 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展