在被右移过的有序数组中查找
在转动过的有序数组中寻找目标值
http://www.nowcoder.com/questionTerminal/7cd13986c79d4d3a8d928d490db5d707
思路:
1.先二分法找到转动的点,
A[mid]和A[0] 做比较大于等于 就说明落到了交接点左边,这时移动 s 指针让mid 向右边靠,反则
移动e 指针让 mid向左靠,最终 s 会落在交接点右边, e 指针会落在交界的 左边
开始:
结束:
2.这样就得到2个有序数组了,接着就是一个二分查找
public int search (int[] A, int target) { //没翻转 if(A[0] <= A[A.length - 1]){ return binarySearch(A, target, 0, A.length - 1); } // 找到翻转的点 int s = 0; int e = A.length - 1; int mid; while (s <= e){ mid = (s + e) / 2; if(A[mid] >= A[0]){ s = mid + 1; }else { e = mid - 1; } } // 确定target在翻转点的右边还是左边 if(target >= A[0]){ return binarySearch(A, target, 0, e); }else { return binarySearch(A, target, s, A.length - 1); } } public int binarySearch(int[] a, int target, int s, int e){ int mid; while (s <= e){ mid = (s + e) / 2; if(a[mid] > target){ e = mid -1; }else if (a[mid] == target){ return mid; }else { s = mid + 1; } } return -1; }