LeetCode-34. Search for a Range

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zy2317878/article/details/80334187

Description

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]

Solution 1(C++)

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res;
        int midl, leftl=0, rightl=nums.size()-1;
        int midr, leftr=0, rightr=nums.size()-1;
        while(leftl<rightl || leftr<rightr){
            midl = leftl + ((rightl-leftl)>>1);
            midr = leftr + ((rightr-leftr+1)>>1);
            if(nums[midl] < target) leftl = midl+1;
            else rightl = midl;
            if(nums[midr] > target) rightr = midr-1;
            else leftr = midr;
        }
        if(rightl < nums.size() && nums[rightl]==target) res.push_back(rightl);
        else res.push_back(-1);
        if(leftr < nums.size() && nums[leftr]==target) res.push_back(leftr);
        else res.push_back(-1);
        return res;
    }
};

算法分析

这一道题还是很有意思的。二分搜索的一道综合题,我把它看做两部分,一部分是找到最小的i,使得nums[i]==target,另一部分是找到最大的i,使得nums[i]==target。二分搜索算法的解释可参考:

其他类似的题目可参考:

  1. LeetCode-33. Search in Rotated Sorted Array
  2. LeetCode-81. Search in Rotated Sorted Array II
  3. LeetCode-153. Find Minimum in Rotated Sorted Array

程序分析

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页