[leetcode]Search in Rotated Sorted Array
简单题吧。用递归解决了。中间有个A[start] <= A[mid]的等号一开始没加。想来因为采用 / 2,mid可能会偏向start一方并mid==start的。
public class Solution { public int search(int[] A, int target) { // Start typing your Java solution below // DO NOT write main() function return search(A, target, 0, A.length - 1); } public int search(int[] A, int target, int start, int end) { if (start > end) return -1; int mid = (start + end) / 2; if (A[mid] == target) return mid; if (A[start] <= A[mid]) { // left part sorted if (target >= A[start] && target < A[mid]) { return search(A, target, start, mid-1); } else if (target > A[mid] || target <= A[end]) { return search(A, target, mid+1, end); } } else // left left part unsorted { if (target >= A[start] || target < A[mid]) { return search(A, target, start, mid-1); } else if (target > A[mid] && target <= A[end]) { return search(A, target, mid+1, end); } } return -1; } }