Search in Rotated Sorted Array

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

Subscribe to see which companies asked this question
**


C++

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int first = 0;
        int last = nums.size();
        while(first != last)
        {
            const int mid = first + (last - first) / 2;
            if(nums[mid] == target)
                return mid;
            if(nums[first] <= nums[mid])
            {
                if(nums[first] <= target && target < nums[mid])
                    last = mid;
                else
                    first = mid + 1;
            }
            else
            {
                if(nums[last-1] >= target && target > nums[mid])
                    first = mid + 1;
                else
                    last = mid;
            }
        }
        return -1;
    }
};

Java

public class Solution {
    public int search(int[] nums, int target) {
        int first = 0;
        int last = nums.length;

        while(first != last)
        {
            int mid = first + (last - first) / 2;
            if(nums[mid] == target)
                return mid;
            if(nums[first] <= nums[mid])
            {
                if(nums[first] <= target && target < nums[mid])
                    last = mid;
                else
                    first = mid + 1;
            }
            else
            {
                if(nums[last-1] >= target && target > nums[mid])
                    first = mid  + 1;
                else
                    last = mid;
            }
        }
        return -1;
    }
}

Python

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        first = 0
        last = len(nums)
        while(first != last):
            mid = first + (last - first) / 2;
            if(nums[mid] == target):
                return mid
            if(nums[mid] >= nums[first]):
                if(nums[first] <= target and target < nums[mid]):
                    last = mid
                else:
                    first = mid + 1
            else:
                if(nums[mid] < target and target <= nums[last-1]):
                    first = mid + 1
                else:
                    last = mid
        return -1
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Shingle_/article/details/52369153
文章标签: 搜索 pivot
个人分类: 积少成多
上一篇旋转数组的最小数字
下一篇Search in Rotated Sorted Array II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭