Leetcode: Search in Rotated Sorted Array II

本文针对允许重复元素的旋转有序数组,提出了一种查找特定目标值的解决方案。文章详细介绍了算法思路,包括如何处理重复元素带来的挑战,并分析了其时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Get idea from Code Ganker (优快云)′solution


Question

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.


Analysis

The solution is similar to the problem Search in Rotated Sorted (Array. However, the thing would be different if duplicates are allowed. In Search in Rotated Sorted Array, we know which half to choose based on the value of left, mid and right.

But if duplicates are allowed, there are some special cases, like [3,3,3,3,3,1,2], [3,1,2,3,3,3,3]. In these cases, nums[mid]=nums[left]=nums[right], and we are not able to know which half should be chosen. So, the idea is to keep movinng left by 1 until num[left]!=num[mid].

Complexity
if all elements are equal, the running time would be O(n)


Solution

class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {boolean}
    def search(self, nums, target):
        if len(nums)==0 or target==None:
            return False

        return self.subsearch(nums,target, 0, len(nums)-1)

    def subsearch(self,nums,target,left,right):
        mid = (left+right)/2
        if nums[mid]==target:
            return True

        if nums[left]>nums[mid]:
            if target>nums[mid] and target<=nums[right]:
                left = mid + 1
            else:
                right = mid - 1
        elif nums[left]<nums[mid]:
            if nums[left]<=target and target<nums[mid]:
                right = mid - 1
            else:
                left = mid + 1
        else:
            left = left + 1


        if left > right:
            return False
        else:
            return self.subsearch(nums,target,left,right)

the difference is that we add

    else:
        left = left + 1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值