从一个旋转的排序数组中寻找一个数字,数组中可能有重复数字,要求时间复杂度O(LogN)。
( 1 1 1 2 4
might become 1 1 2 4 1
).
You are given a target value to search. If found in the array return true, otherwise return false.
思路:二分查找,需要注意的是,若中间数字跟最左端数字相等时,去掉最左端的数字,然后递归查找。代码如下:
class Solution { bool search(int A[], int n, int target) { return search(A,0,n-1,target); } bool search(int *ary, int start, int end, int target) { if (start > end) return false; int mid = start + ((end-start)>>1); int number0 = ary[start]; int number = ary[mid]; int number1 = ary[end]; if (number == target) return true; if (number > number0) { if(target < number0 || target > number) return search(ary,mid+1,end,target); else return search(ary,start,mid-1,target); } else if(number < number0) { if (target > number1 || target < number) return search(ary,start,mid-1,target); else return search(ary,mid+1,end,target); } // number == number0 return search(ary,start+1,end,target); } };