LeetCode Search for a Range (二分查找)

本文介绍了一种在有序数组中查找特定目标值起始和结束位置的算法,该算法的时间复杂度为O(logN),通过一次二分查找找到目标值,再向左右两侧遍历确定范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
给定一个有序数组和一个目标值,查找出目标值在数组中出现的发生下标区域。时间复杂度要求log(N)。

解法

刚开始以为下标也需要用二分来查找,但看讨论发现大家都是找出目标值然后再向两边搜索-_-b,这样做的话,最差的情况下(数组里的数全都一样)就是O(N)了,但是也能过。

class Solution
{
public:
    vector<int> searchRange(vector<int>& nums, int target)
    {
        int left = 0;
        int right = nums.size() - 1;
        int index_a = -1;
        int index_b = -1;
        int index = 0;
        bool    flag = false;

        while(left <= right)
        {
            int mid = (left + right) >> 1;
            if(nums[mid] == target)
            {
                flag = true;
                index = mid;
                break;
            }
            else
                if(nums[mid] < target)
                    left = mid + 1;
                else
                    right = mid - 1;
        }
        if(flag)
            index_a = index;
        while(index_a >= 1 && nums[index_a - 1] == target)
            index_a --;
        if(flag)
            index_b = index;
        while(index_b < nums.size() - 1 && nums[index_b + 1] == target)
            index_b ++;

        vector<int> rt = {index_a,index_b};
        return  rt;
    }
};

转载于:https://www.cnblogs.com/xz816111/p/5889878.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值