Search in Rotated Sorted Array II

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.

这题是follow up. 关键是在l,r,mid都相等,无法判断哪段有序时该怎么处理.此时可以根据等于mid的情况,对l和r做加1和减1处理.最坏情况,为数组全部元素相同,且不等于target.时间复杂度O(n).

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: bool
        """
        if not nums:
            return False
        l = 0
        r = len(nums) - 1
        while l + 1 < r:
            mid = l + (r - l)/2
            if nums[mid] == target:
                return True
            if nums[mid] > nums[l]:
                if nums[l] <= target <= nums[mid]:
                    r = mid
                else:
                    l = mid
            elif nums[mid] < nums[r]:
                if nums[mid] < target <= nums[r]:
                    l = mid
                else:
                    r = mid
            else:
                if nums[l] == nums[mid]:
                    l += 1
                if nums[r] == nums[mid]:
                    r -= 1
        if nums[l] != target and nums[r] != target:
            return False
        else:
            return True

 

posted on 2016-08-21 12:12  Sheryl Wang  阅读(146)  评论(0编辑  收藏  举报

导航