/* * 81. Search in Rotated Sorted Array II * 2016-5-13 by Mingyang * 这就是I的升级版,所有思路一模一样 * 1.如果右边sort,并且target比中间小,那么肯定在左边, * 如果A[mid] == A[high],那么high--,因为不能判断哪边是sorted * 如果A[mid]>A[high]那么左边sort,那么只需要看最左边和target的关系 * 这里还需要注意的就是while (low <= high)一定需要等于符号 */ public boolean search2(int[] A, int target) { if (A == null || A.length == 0) return false; int low = 0; int high = A.length - 1; while (low <= high) { int mid = (low + high) / 2; if (target < A[mid]) { if (A[mid] < A[high])// right side is sorted high = mid - 1;// target must in left side else if (A[mid] == A[high]) // cannot tell right is sorted, move pointer high----这一部分就是多加出来的 high--; else // left side is sorted if (target < A[low]) low = mid + 1; else high = mid - 1; } else if (target > A[mid]) { if (A[low] < A[mid])// left side is sorted low = mid + 1;// target must in right side else if (A[low] == A[mid]) // cannot tell left is sorted, move pointer low----这一部分就是多加出来的 low++; else // right side is sorted if (target > A[high]) high = mid - 1; else low = mid + 1; } else return true; } return false; }