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

2019.2.12

题目描述:

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given targetvalue.

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在一个升序数组中的首尾index,不过要求时间复杂度为O(log n)。

解法一:

因为是升序数组且要求时间复杂度是O(log n),所以可以考虑二分法查找。利用两次二分查找,先查找左边界,再查找右边界即可。

C++代码:

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

猜你喜欢

转载自blog.csdn.net/weixin_41637618/article/details/87064293