LeetCode 33.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.

分析与解答:

这个数组的特点是,如果pivot在区间(a,b]内的话,那么a一定是大于等于b的。依然是用二分搜索,只是在边界条件的判断上根据数组的特点做一些改动。

class Solution {
public:
int search(int A[], int n, int target) {
    int left = 0, right = n;
    while(left != right) {
        int mid = left + (right - left) / 2;
        if(target == A[mid])
            return mid;
        if(target < A[mid]) {
            if(A[right - 1] >= target && A[right - 1] < A[mid] ) //保留右边
                left = mid + 1;
            else
                right = mid;
        } else {
            if(A[left] <= target && A[left] > A[mid])//保留左边
                right = mid;
            else
                left = mid + 1;
        }
    }
    return -1;
}
};

你可能感兴趣的:(array,search,binary)