[Leetcode]Search in Rotated Sorted Array II

来源:互联网 发布:ubuntu 禁用访客 编辑:程序博客网 时间:2024/06/03 17:35

题目

Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

题目要求

此题是Search in Rotated Sorted Array题目的扩展,要求判断经过翻转过的有序数组中是否含有target这个值。两个题目的差别在于有序数组中是否有重复的数字。两道题都是采用二分法,只是两道题的在条件判断时会有一些变种。

解题思路

  1. 数组中没有重复数字。
    [left middle]和[middle right]至少有一个是有序的,我们就判断target是否在有序的那一半,如果在,则选择有序的那一半,否则选择无序的那一半。
  2. 数组中有重复数字
    这种情况的难点在于,[left middle]和[middle right]无法直接通过比较两端指针指向判断是否有序。比如[1 3 1 1 1]这个数组只是根据left middle 和right并不能分辨出哪段数据是无序的。所以进行一个额外的操作,如果left,middle 和right指针指向的值都相等时,让left和right都向middle移动一次,这样最后就可以像1一样进行相同的判断了

代码

class Solution(object):    def search(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: bool        """        left, right = 0, len(nums) - 1        while left <= right:            middle = (left + right) / 2            if nums[middle] == target:                return True            if nums[left] == nums[middle] == nums[right]:                left += 1                right -= 1                continue            if nums[left] <= nums[middle]:                if target >= nums[left] and target < nums[middle]:                    right = middle - 1                else:                    left = middle + 1            elif nums[middle] <= nums[right]:                if target > nums[middle] and target <= nums[right]:                    left = middle + 1                else:                    right = middle - 1        return False
0 0
原创粉丝点击