LeetCode题解:Search in Rotated Sorted Array

Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

思路:

首先用二分法找到rotate的pivot,然后再根据pivot继续二分法找到相应的数值。

题解:

class Solution {
public:
int pivot_search (int* A, int n)
{
    int lower = 0;
    int upper = n - 1;

    if (A[upper] > A[lower])
        return n - 1;
    
    while (upper - lower > 1)
    {
        int pivot = (lower + upper) / 2;
        
        if (A[pivot] > A[lower])    // pivot at lower side
            lower = pivot;
        else if (A[pivot] < A[upper])
            upper = pivot;
    }
    return lower;
}

int search (int A[], int n, int target)
{
    if (n == 0 || A == 0)
        return -1;
        
    int pivot = pivot_search (A, n);

    int lower, upper;
    if (A[0] > target)
    {
        lower = pivot + 1;
        upper = n - 1;
    }
    else
    {
        lower = 0;
        upper = pivot;
    }

    while(lower < upper)
    {
        int mid = (lower + upper) / 2;

        if (A[mid] > target)
            upper = mid - 1;
        else if (A[mid] < target)
            lower = mid + 1;
        else 
            return mid;
    }
    if (lower < n && A[lower] == target)
        return lower;
    return -1;
}
};


你可能感兴趣的:(LeetCode)