62.Search in Rotated Sorted Array *

public class Solution {
/** 
 *@param A : an integer rotated sorted array
 *@param target :  an integer to be searched
 *return : an integer
 */
public int search(int[] A, int target) {
    // write your code here
    if (A == null) return -1;
    int length = A.length;
    if (length == 0) return -1;
    int last = A[length - 1];
    int start = 0;
    int end = length - 1;
    if (last == target) return end;
    while (start + 1 < end) {
        int mid = start + (end - start) / 2;
        if (A[mid] == target) return mid;
        if (target < last) {
            if (A[mid] < target) start = mid;
            else if (A[mid] > target && A[mid] < last) end = mid;
            else if (A[mid] > target && A[mid] > last) start = mid;
        } else {
            if (A[mid] > target) end = mid;
            else if (A[mid] < target && A[mid] < last) end = mid;
            else if (A[mid] < target && A[mid] > last) start = mid;
        }
    }
    if (A[start] == target) return start;
    if (A[end] == end) return end;
    return -1;
}

}

你可能感兴趣的:(62.Search in Rotated Sorted Array *)