[Leetcode] Search in Rotated Sorted Array

来源:互联网 发布:网络招聘平台对比 编辑:程序博客网 时间:2024/05/21 12:42

题目:

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). 

0 0
原创粉丝点击