您的位置:首页 > 其它

Find Minimum in Rotated Sorted Array II

2015-08-30 21:41 239 查看
题目:

Follow up for "Find Minimum in Rotated Sorted Array":

What if duplicates are allowed?
Would this affect the run-time complexity? How and why?

Suppose a sorted array 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
).

Find the minimum element.

The array may contain duplicates.
解题思路:
此题与Find Minimum in Rotated Sorted Array I的最大区别就是可能出现duplicates,一中行之有效的办法就是先去重,然后再对其用1的办法。

代码如下所示:

class Solution(object):

def findMin(self, nums):

"""

:type nums: List[int]

:rtype: int

"""

def deduplicate(nums):

while nums[0]==nums[-1] and len(nums)>1:

nums.pop()

i,j = 0,1

while j<len(nums) and len(nums)>1:

if nums[i]!=nums[j]:

i += 1

j += 1

else:

key = nums[i]

while j<len(nums) and nums[j]==nums[i]:

j += 1

if j<len(nums):

for x in range(j-i-1):

nums.remove(key)

j = i+1

else:

return nums[:i+1]

return nums[:]

nums = deduplicate(nums)

lo, hi = 0, len(nums)-1

while lo<hi:

mid = (lo+hi)/2

if nums[mid]<nums[hi]:

hi = mid

else:

lo = mid+1

return nums[lo]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: