zoukankan      html  css  js  c++  java
  • LeetCode_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].
    

      

    class Solution {
    public:
        vector<int> searchRange(int A[], int n, int target) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int min,max,mid;
            int i, j;
            min = 0;
            max = n-1;
            vector<int> result ;
            if(A[0] > target|| A[n-1] <target)
            {
                result.push_back(-1);
                result.push_back(-1);
                return result ;
            }
            while(min <= max)
            {
                mid = min + (max - min)/2;
                if(A[mid] == target)
                   break;
                 else if(A[mid] < target)
                     min = mid + 1;
                   else
                     max = mid - 1;
            }
            
          if( A[mid] == target ) {
                i=j = mid;
                while(i>=0 && A[i] == target)i-- ;
                while(j<= n-1 && A[j] == target) j++ ;
                 i++;j--;
            result.push_back(i);
            result.push_back(j) ;
          }else{
           
               result.push_back(-1);
                result.push_back(-1);  
          }
            return result ;
        }
    };
    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    【convertio.co】免费在线文档转化神器
    成长需熬过“四苦”
    岁月饶过谁
    致我的未来
    一定要相信自己
    奋斗的意义是什么?
    一生一世一双人,半醉半醒半浮生
    逆境中的自己
    怎样才能让人看到你呢
    2020 遇见更好的自己
  • 原文地址:https://www.cnblogs.com/graph/p/3043154.html
Copyright © 2011-2022 走看看