您的位置:首页 > 其它

[Leetcode] Search in Rotated Sorted Array

2014-10-18 04:59 344 查看
题目:

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 lower_bound = 0;
        int upper_bound = n - 1;
        while (lower_bound <= upper_bound) {
            int mid = (lower_bound + upper_bound) / 2;
            if (A[mid] == target) {
                return mid;
            } else if (A[mid] >= A[lower_bound]) {   //left part consistent
                if (A[lower_bound] <= target && A[mid] > target) {   //go left
                    upper_bound = mid - 1;
                } else {   //go right
                    lower_bound = mid + 1;
                }
            } else {   //right part consistent
                if (A[upper_bound] >= target && A[mid] < target) {   //go right
                    lower_bound = mid + 1;
                } else {   //go left
                    upper_bound = mid - 1;
                }
            }
        }
        return -1;
    }
};


总结:复杂度为O(log n). 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: