Search in Rotated Sorted Array

LeetCode #33


Description:

Suppose an array sorted in ascending order 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.

Example:

Note

Idea:

这里用的search方式是[left, right).

Time: O(logn).

Code:

class Solution {
public:
    int search(vector<int>& nums, int target) {

        int begin=0;
        int end=nums.size();

        while(begin < end){
            int mid = begin + (end-begin)/2;
            if(nums[mid] == target) return mid;

            if(nums[begin]<=nums[mid]){ // 这种情况包括 begin==mid
                if(nums[begin]<=target && target<nums[mid]) end=mid;
                else begin=mid+1;
            }
            else{
                if(nums[mid]<target && target<=nums[end-1]) begin = mid+1;
                else end=mid;
            }
        }
        return -1;

    }
};

results matching ""

    No results matching ""