zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    LCA最近公共祖先Tarjan(离线)
    51nod 1135 原根
    51nod 1134最长递增子序列
    51nod 1130 斯特林公式
    51nod 1186 Miller-Rabin素数测试
    51Nod 1257 背包问题 V3
    另类求组合数
    Gym
    msp430项目编程45
    msp430项目编程44
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5792449.html
Copyright © 2011-2022 走看看