关闭

Search in Rotated Sorted Array

标签: 搜索pivot
98人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:46300次
    • 积分:1608
    • 等级:
    • 排名:千里之外
    • 原创:119篇
    • 转载:6篇
    • 译文:0篇
    • 评论:0条