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

Posted qiulinzhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

以上是关于34. Find First and Last Position of Element in Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

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

[leetcode][34] Find First and Last Position of Element in Sorted Array

[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array

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

Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)

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