Question:
Follow up for "search in rotated sorted array ":
What ifDuplicatesAre allowed?
Wocould this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
Note:
1) compared with 1, there are only repeated numbers, and binary search is still used as a whole.
2) Method 2:
Implementation:
I. Implementation:
1 class solution {2 public: 3 bool search (int A [], int N, int target) {4 If (n = 0 | n = 1 & A [0]! = Target) return false; 5 if (a [0] = target) return true; 6 int I = 1; 7 while (A [I-1] <= A [I]) I ++; 8 9 bool pre = binary_search (A, 0, I, target); 10 bool Pos = binary_search (A, I, n-I, target ); 11 return pre = false? POs: Pre; 12} 13 private: 14 bool binary_search (int * B, int Lo, int Len, int goal) 15 {16 int low = lo; 17 int high = lo + len-1; 18 while (low <= high) 19 {20 int middle = (low + high)/2; 21 if (Goal = B [Middle]) // find, return index22 return true; 23 else if (B [Middle] <goal) // on the right side 24 low = middle + 1; 25 else // on the left side 26 high = middle-1; 27} 28 return false; // No, -129} 30 };
2. Open-Source implementation on the Internet:
1 class Solution { 2 public: 3 bool search(int A[], int n, int target) { 4 int low=0; 5 int high=n-1; 6 while(low<=high) 7 { 8 const int middle=(low+high)/2; 9 if(A[middle]==target) return true;10 if(A[low]<A[middle])11 {12 if(A[low]<=target&&target<A[middle])13 high=middle-1;14 else15 low=middle+1;16 }17 else if(A[low]>A[middle])18 {19 if(A[middle]<target&&target<=A[high])20 low=middle+1;21 else 22 high=middle-1;23 }24 else25 low++;26 }27 return false;28 }29 };