Search for a Range

Posted RenewDo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Search for a Range相关的知识,希望对你有一定的参考价值。

先利用二分法找到目标值,然后分别在其前半部分,后半部分用二分法找到目标值的最小范围,最大范围

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,mid;
        int mid1,high1,mid2,low2;
        while(low<=high &&low>=0)
        {
            mid=(low+high)/2;
            if(nums[mid]==target)
            {
                if(nums[low]==target)res[0]=low;
                else
                {
                    high1=mid;
                    while(low<high1)
                    {
                      mid1=(high1+low)/2; 
                      if(nums[mid1]==target) 
                          if(nums[mid1-1]!=target){res[0]=low=mid1;break;}
                          else high1=mid1-1;
                      else low=mid1+1;
                    }
                    res[0]=low;
                }
                if(nums[high]==target) res[1]=high;
                else{
                    low2=mid;
                     while(low2<high)
                    {
                      mid2=(high+low2)/2; 
                      if(nums[mid2]==target) 
                          if(nums[mid2+1]!=target) {res[1]=low2=mid2;break;}
                          else low2=mid2+1;
                      else high=mid2-1;
                    }
                    res[1]=low2;
                }
                break;
            }
            else if(nums[mid]<target) low=mid+1;
                  else high=mid-1;
        }
        return res;
    }
};

我的逻辑太饶了,下面是网上的大牛之作

vector<int> searchRange(int A[], int n, int target) {
    int i = 0, j = n - 1;
    vector<int> ret(2, -1);
    // Search for the left one
    while (i < j)
    {
        int mid = (i + j) /2;
        if (A[mid] < target) i = mid + 1;
        else j = mid;
    }
    if (A[i]!=target) return ret;
    else ret[0] = i;

    // Search for the right one
    j = n-1;  // We don‘t have to set i to 0 the second time.
    while (i < j)
    {
        int mid = (i + j) /2 + 1;   // Make mid biased to the right
        if (A[mid] > target) j = mid - 1;  
        else i = mid;               // So that this won‘t make the search range stuck.
    }
    ret[1] = j;
    return ret; 
}

 

以上是关于Search for a Range的主要内容,如果未能解决你的问题,请参考以下文章

Search for a Range

Search for a Range

Search for a Range

[Leetcode] Search for a Range

Search for a Range

Search for a Range