[LeetCode] Search in Rotated Sorted Array

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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.

题目思路

这个题目是对常规的二分查找的一个变形。基本的思路就是用二分查找。但是区别在于:二分查找进行二分的条件是判断target和nums[mid]之间的大小;而这里进行二分的条件是更加复杂,不仅需要判断nums[mid]在数组的左半部分还是右半部分,而且要判断target和子数组两端元素的关系。

另外,此题的难点在于边界条件的把握,什么时候取等号需要认真考虑。

Python代码

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if nums==[]:
            return -1
        end=len(nums)-1
        start=0
        while start<=end:
            mid=(start+end)/2
            if nums[mid]==target:
                return mid
            if nums[mid]>=nums[start]:
                if nums[start]<=target and target<nums[mid]:
                    end=mid
                else:
                    start=mid+1
            else:
                if nums[end]>=target and nums[mid]<target:
                    start=mid+1
                else:
                    end=mid
        return -1         

 

以上是关于[LeetCode] Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode&Python] Problem 700. Search in a Binary Search Tree

[Leetcode]700. Search in a Binary Search Tree

LeetCode Verify Preorder Sequence in Binary Search Tree

Leetcode[33]-Search in Rotated Sorted Array

LeetCode 700 Search in a Binary Search Tree 解题报告

#Leetcode# 33. Search in Rotated Sorted Array