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.,
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]
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 7might 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]
相关文章推荐
- 就是这么做了,没别的意思
- POJ 3667 Hotel
- scanf("%s")和scanf("%c")区别
- hdu 5424 Rikka with Graph II 判n点n边的图是否为哈密顿通路
- jQuery操作DOM元素
- Codeforces Round #318-(C. Bear and Poker)
- 堆和栈
- 大龄屌丝自学笔记--Java零基础到菜鸟--014
- B、Infoplane in Tina Town-----(BestCoder Round #51 (div.2) )
- [Bluetooth Core V4.2 ] VOL2, PartB, 4 Logical Transports
- shell展开
- 第5组UI "让你的界面酷炫到底"-ViewAniMator之ViewSwitcher、ImageSwitcher(图像切换器)、TextSwitcher(文本切换器)、ViewFlipper
- IOS UITableView拖动排序功能
- [JavaWeb基础] 014.Struts2 标签库学习
- VMware虚拟机中nat网络模式的设置方法
- 关于eclipse使用中,真机测试无法打开File Explorer中data目录无法打开的问题
- hibernate使用本地sql语句查询,解决List<Object[]>转换成List<实体>
- Python3 Hovercraft创建impressive.js演示文档(三)
- iOS_UI_2_Label
- uva 11806 Cheerleaders 容斥原理