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

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

给定一个有序数组,可能包含有重复元素,问target在数组中的起始位置和结束位置,要求复杂度 \(O(logN)\)
------------------------------------------------------------------
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 5
Output: [0,0]

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int lo = 0, hi = nums.size()-1;
        if (hi==-1)
        {
            vector<int> result={-1,-1};
            return result;
        }

        while(lo < hi && nums[lo] != nums[hi]) // nums[lo]==nums[hi]时,从lo 到hi都是相同的数字,因此可以直接退出
        {
            int mi = (lo + hi)>>1;
            if(nums[mi]<target)
                lo = mi + 1;
            else if(target < nums[mi])
                hi = mi -1;
            else // 如果 target和nums[mi]相等,则 lo+1或者hi-1 进行选择
                if(target==nums[lo])// 如果target和nums[lo]相等,lo不动,动hi
                    --hi;
                else // 如果target 和nums[lo]不相等,则动lo,hi不动
                    ++lo;

        }
        vector<int> result;
        if(nums[lo]!=target)
            lo = -1,hi = -1;            
        result.push_back(lo);
        result.push_back(hi);
        return result;
    }
};

结果:

Runtime: 8 ms, faster than 84.44% of C++ online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Find First and Last Position of Element in Sorted Array.

原文链接: https://www.cnblogs.com/qiulinzhang/p/12530748.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/336569

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午10:42
下一篇 2023年3月1日 下午10:43

相关推荐