LeetCode 33. Search in Rotated Sorted Array

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.

Subscribe to see which companies asked this question.

一串有序数字,这串数字有可能前面一部分挪到后面了。 给你一个目标值, 求这个数字在这串数字中的位置。

直接二分, 只不过需要事先判断一下就好了。

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if(nums.size() == 0)
            return -1;
        int s = nums.size() - 1;
        int b = 0, e = s;
        if(target >= nums[0])
        {
            while(b < e)
            {
                int mid = (b + e) / 2;
                if(nums[mid] == target)
                    return mid;
                else if(nums[mid] > target)
                    e = mid - 1;
                else
                {
                    if(nums[mid] < nums[0])
                        e = mid - 1;
                    else
                        b = mid + 1;
                }
            }
        }
        else
        {
            while(b < e)
            {
                int mid = (b + e)/2;
                if(nums[mid] == target)
                    return mid;
                else if(nums[mid] < target)
                    b = mid + 1;
                else
                {
                    if(nums[mid] < nums[0])
                        e = mid - 1;
                    else
                        b = mid + 1;
                }
            }
        }
        if(nums[b] == target)
            return b;
        else
            return -1;
    }
};
posted @ 2017-03-20 22:44  aiterator  阅读(80)  评论(0编辑  收藏  举报