[Leetcode]81. Search in Rotated Sorted Array II
81. Search in Rotated Sorted Array II
(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 Input: nums = [2,target = 3 This is a follow up problem to Search in Rotated Sorted Array,where nums may contain duplicates. 我的的代码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]这类情况,没想好怎么做,所以
别人的代码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]这类情况,没想好怎么做,所以
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |