leetcode 34. Find First and Last Position of Element in Sorted Array 二分查找

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]

两次二分查找

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int n=nums.size();
        vector<int> res={-1,-1};
        int lo=0,hi=n;
        while(lo<hi){
            int mi=(lo+hi)/2;
            if(nums[mi]>=target)hi=mi;
            else lo=mi+1;
        }
        if(lo==n||nums[lo]!=target)return res;
        res[0]=lo;
        hi=n;
        while(lo<hi){
            int mi=(lo+hi)/2;
            if(nums[mi]>target)hi=mi;
            else lo=mi+1;
        }
        res[1]=lo-1;
        return res;
    }
};
posted @ 2020-07-25 11:17  winechord  阅读(73)  评论(0编辑  收藏  举报