程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode]Search in Rotated Sorted Array II

[LeetCode]Search in Rotated Sorted Array II

編輯:C++入門知識

[cpp] 
class Solution { 
//classified discussion  
//1. Based on the property of rotated array, there may or may not have one sorted sequence   
//when one sequence is divided into two parts    
//2. make decision under all these cases  
public: 
    bool search(int A[], int n, int target) { 
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function  
        return BinarySearch(A, n, target); 
    } 
 
 
    bool BinarySearch( int* A, int n, int target )  
    { 
        //throw std::exception("The method or operation is not implemented.");  
        int l = 0; 
        int r = n-1; 
        while (l <= r) 
        { 
            int m = l+(r-l)/2; 
            if(A[m] == target) return true; 
            if (A[l] < A[m])//left subsequence sorted  
            { 
                if(A[l] <= target && target < A[m]) 
                    r = m-1; 
                else l = m+1; 
            } 
            else if (A[m] < A[r]) 
            { 
                if(A[m] < target && target <= A[r]) 
                    l = m+1; 
                else r = m-1; 
            } 
            else if (A[l] == A[m])//A[m] is not the target, so remove en element equal to A[m] is safe  
                l++; 
            else if(A[m] == A[r])//ditto  
                r--; 
        } 
        return false; 
    } 
}; 

class Solution {
//classified discussion
//1. Based on the property of rotated array, there may or may not have one sorted sequence
//when one sequence is divided into two parts 
//2. make decision under all these cases
public:
 bool search(int A[], int n, int target) {
  // Start typing your C/C++ solution below
  // DO NOT write int main() function
  return BinarySearch(A, n, target);
 }


 bool BinarySearch( int* A, int n, int target )
 {
  //throw std::exception("The method or operation is not implemented.");
  int l = 0;
  int r = n-1;
  while (l <= r)
  {
   int m = l+(r-l)/2;
   if(A[m] == target) return true;
   if (A[l] < A[m])//left subsequence sorted
   {
    if(A[l] <= target && target < A[m])
     r = m-1;
    else l = m+1;
   }
   else if (A[m] < A[r])
   {
    if(A[m] < target && target <= A[r])
     l = m+1;
    else r = m-1;
   }
   else if (A[l] == A[m])//A[m] is not the target, so remove en element equal to A[m] is safe
    l++;
   else if(A[m] == A[r])//ditto
    r--;
  }
  return false;
 }
};

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved