LeetCode: Search in Rotated Sorted Array

Title:

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.

 

思路:还是二分搜索,但是对于一个中间值,如何处理是左加还是右加呢?考虑下,旋转之后的数组,中间值会将原来的数组划分为左右两个数组,其中一个是有序的。所以我们需要做的事就是判断那边是有序的。如何判断有序呢?只要将中间值和最左边的值比较,如果大于,则左边是有序,如果小于,则右边有序,如果相等,则有重复元素只能一个个处理。

class Solution {
public:
    int search(int A[], int n, int target) {
        int l = 0;
        int h = n-1;
        while (l <= h){
            int m = (l+h)/2;
            if (A[m] == target)
                return m;
            if (A[m] > A[l]){
                if (target >= A[l] && target < A[m])
                    h = m-1;
                else
                    l = m+1;
            }
            else if (A[m] < A[l]){
                if (target <= A[h] && target > A[m])
                    l = m+1;
                else
                    h = m-1;
            }
            else
                l++;
        }
        return -1;
    }
};

 

posted on 2015-04-21 14:24  月下之风  阅读(203)  评论(0编辑  收藏  举报

导航