[LeetCode] Search in Rotated Sorted Array ii
阿新 • • 發佈:2017-07-05
become duplicate 代碼 elf end sort medium etc 判斷
題目內容
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
題目思路
本題難度:medium
這個題目是基於上一道題Search in Rotated Sorted Array改進的。在上一道題當中,nums[start]和nums[mid]的判斷中,將<和=是聯合在一起進行判斷的。在本題當中,假如nums[start]==nums[mid],那麽將start+=1,將start轉移到不等的地方。
Python代碼
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if nums==[]: return False end=len(nums)-1 start=0 while start<=end: mid=(start+end)/2 if nums[mid]==target: return True if nums[mid]>nums[start]: if nums[start]<=target and target<nums[mid]: end=mid else: start=mid+1 elif nums[mid]<nums[start]:if nums[end]>=target and nums[mid]<target: start=mid+1 else: end=mid else: start+=1 return False
[LeetCode] Search in Rotated Sorted Array ii