加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[Leetcode]81. Search in Rotated Sorted Array II

发布时间:2020-12-14 04:25:27 所属栏目:大数据 来源:网络整理
导读:81. Search in Rotated Sorted Array II 本题难度: Medium Topic: Binary Search 类似[Lintcode]62. Search in Rotated Sorted Array/[Leetcode]33. Search in Rotated Sorted Array Description Search in Rotated Sorted Array II Suppose an array sorted

81. Search in Rotated Sorted Array II

  • 本题难度: Medium
  • Topic: Binary Search
    类似[Lintcode]62. Search in Rotated Sorted Array/[Leetcode]33. Search in Rotated Sorted Array

    Description

  1. Search in Rotated Sorted Array II
    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,[0,1,2,5,6] might become [2,6,2]).

You are given a target value to search. If found in the array return true,otherwise return false.

Example 1:

Input: nums = [2,2],target = 0
Output: true
Example 2:

Input: nums = [2,target = 3
Output: false
Follow up:

This is a follow up problem to Search in Rotated Sorted Array,where nums may contain duplicates.
Would this affect the run-time complexity? How and why?

我的的代码

class Solution:
    def search(self,A: ‘List[int]‘,target: ‘int‘) -> ‘bool‘:
        # write your code here
        if A  == []:
            return False
        l = 0
        r = len(A)-1#注意!
        f = -1 # breakpoint
        if len(A) == 1:
            return A[0] == target
        for i in range(1,len(A)):
            if A[i-1]>A[i]:
                f = i
        if f == -1:
            l = 0
            r = len(A) - 1
        else:
            if target>=A[0]:
                l = 0
                r = f-1
            else:
                l = f
                r = len(A)-1

        while(l<=r):
            m = (l+r)//2
            if A[m] == target:
                return True
            else:
                if A[m]>target:
                    r = m-1
                else:
                    l = m+1

        return False

思路

如果遇到[2,2]这类情况,没想好怎么做,所以

  • 时间复杂度: O(log(n))

别人的代码

def search(self,nums,target):
    l,r = 0,len(nums)-1
    while l <= r:
        mid = l + (r-l)//2
        if nums[mid] == target:
            return True
        while l < mid and nums[l] == nums[mid]: # tricky part
            l += 1
        # the first half is ordered
        if nums[l] <= nums[mid]:
            # target is in the first half
            if nums[l] <= target < nums[mid]:
                r = mid - 1
            else:
                l = mid + 1
        # the second half is ordered
        else:
            # target is in the second half
            if nums[mid] < target <= nums[r]:
                l = mid + 1
            else:
                r = mid - 1
    return False

思路

如果遇到[2,2]这类情况,没想好怎么做,所以

  • 时间复杂度: average : O(log(n)) worst O(n)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读