LeetCode34. Find First and Last Position of Element in Sorted Array(C++)

Given an array of integers nums sorted in ascending order, 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].

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]

解题思路:二分法先找到一个target

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int low=0,high=nums.size()-1,result=-1;
        vector<int>a;
        while(low<=high){
            int mid=(low+high)/2;
            if(nums[mid]==target){
                result=mid;
                break;
            }
            else if(nums[mid]>target)
                high=mid-1;
            else
                low=mid+1;
        }
        if(result==-1){
            a.push_back(-1);
            a.push_back(-1);
        }
        else{
            int p=result,q=result;
            while(p>=0&&nums[p]==target)
                p--;
            while(q<nums.size()&&nums[q]==target)
                q++;
            a.push_back(p+1);
            a.push_back(q-1);
        }
        return a;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/86468470
今日推荐