Search for a Range——稍微升级版的二分查找

Given a sorted array of integers, 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

网上看到的思路更好,网上说的是,先用二分法找到左端点,再用二分搜索找到右端点。问题即得到解决。

我的思路不太好,我是首先找到等于target的索引(即以前用烂了的二分查找),然后以此为中心向两边扩。

1:我的方法:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int len=nums.size();
        int l=0,r=len-1;
        int mid;
        vector<int>res;
        int flag=0;
        while(l<=r)
        {
            mid=l+(r-l)/2;
            if(nums[mid]<target)
                l=mid+1;
            else if(nums[mid]>target)
                r=mid-1;
            else
            {
                flag=1;
                break;
            }
        }
        if(flag==0)
        {
             res.push_back(-1);
             res.push_back(-1);
        }
        else
        {
            l=mid;
            r=mid;
            while(l>=0&&nums[l]==target)
            {
                if(nums[l]==target)
                l--;
            }
            while(r<=len-1&&nums[r]==target)
            {
                if(nums[r]==target)
                r++;
            }
            
             res.push_back(l+1);
             res.push_back(r-1);
        }
       return res;    
    }
};

2:网上看到直接二分查找左右端点的方法:

class Solution {
public:
    int begin = -1, end = -1;
    vector<int> searchRange(int A[], int n, int target) {
       vector<int>ans;
       find(A,0,n-1,target);
       ans.push_back(begin);
       ans.push_back(end);
       return ans;
    }
    void find(int A[], int l, int r, int target){
      if(l > r) return ;
      int mid = (l+r) >> 1;
      if(A[mid] == target){
        if(begin == -1 || begin > mid)
          begin = mid;
        end = max(mid, end);
        find(A,l,mid-1,target);
        find(A,mid+1,r,target);
      }
      else if(A[mid] < target)
        find(A,mid+1,r,target);
      else
        find(A,l,mid-1,target);
    }
};

 

3:直接用 C++ STL 的 lower_boundupper_bound 偷懒。

  class Solution {  
    public:  
        vector<int> searchRange(int A[], int n, int target) {  
            int* lower = lower_bound(A, A + n, target);  
            int* upper = upper_bound(A, A + n, target);  
            if (*lower != target)  
                return vector<int> {-1, -1};  
            else  
                return vector<int>{lower - A, upper - A - 1};  
        }  
    };  
 
   

 

 

转载于:https://www.cnblogs.com/qiaozhoulin/p/4581391.html

你可能感兴趣的:(runtime,c/c++)