如果有重复数字,那么,如果A[m]>=A[l],那么[l,m]为递增序列的假设就不能成立了,比如如下数据 [1,3,1,1,1] 解决办法: 如果A[m]>=A[l]不能确定递增,那就把它拆分成两个条件 1. A[m]>A[l] 递增 2. A[m] ==A[l] 确定不了,那就l++,往下看一步即可。 bool search(int A[], int n, int target) { int start = 0; int end = n-1; while(start <= end) { int mid = (start+end)/2; if(A[mid] == target) return true; if(A[start] < A[mid]) { if(target>=A[start] && target<A[mid]) end = mid-1; else start = mid+1; } else if(A[start] > A[mid]) { if(target>A[mid] && target<=A[end]) start = mid+1; else end = mid-1; } else //skip duplicate one, A[start] == A[mid] start++; } return false; }
Tuesday, November 25, 2014
Search in Rotated Sorted Array II
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment