Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
原题链接(点我)这题和Search in Rotated Sorted Array问题类似,不过这个题允许元素重复,如果有元素重复,此时采取最保守的策略,一次缩小一个范围。
class Solution { public: bool search(int A[], int n, int target) { if(A==NULL || n<=0) return false; int begin = 0, end = n-1, mid = 0; while(begin<=end){ mid = (begin+end)/2; if(A[mid] == target) return true; if(A[mid] < A[end]){ //后半段有序 if(A[end]>=target && A[mid]<target) begin = mid+1; else end = mid - 1; }else if(A[mid] > A[end]){ //前半段有序 if(A[begin]<=target && A[mid] > target) end = mid-1; else begin = mid+1; }else // 最保守策略,缩小一个范围 --end; } return false; } };
[LeetCode] Search in Rotated Sorted Array II [36],布布扣,bubuko.com
[LeetCode] Search in Rotated Sorted Array II [36]
原文:http://blog.csdn.net/swagle/article/details/30487759