首页 > 其他 > 详细

[LeetCode] Search in Rotated Sorted Array

时间:2017-07-04 12:53:08      阅读:325      评论:0      收藏:0      [点我收藏+]

题目内容

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

原文:http://www.cnblogs.com/chengyuanqi/p/7115846.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!