LintCode Q160 Find Minimum in Rotated Sorted Array II in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年12月27日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
# @param nums: a rotated sorted array
# @return: the minimum number in the array
def findMin(self, nums):
# find break point in the input array
# The array may contain duplicates.
# time complexity: O(log(n))
# invalide input
if len(nums) == 0:
return
lo, hi = 0, len(nums) - 1
target = nums[-1]
return self.binarySearch(nums, lo, hi, target)
def binarySearch(self, nums, lo, hi, target):
res = target
while lo <= hi:
mid = lo + (hi - lo)/2
if nums[mid] < target:
hi = mid - 1
res = nums[mid]
elif nums[mid] > target:
lo = mid + 1
else: # nums[mid] == target
if lo == hi: # and nums[lo] == target
return nums[lo]
else:
return min(self.binarySearch(nums, lo, mid - 1, nums[mid - 1]), self.binarySearch(nums, mid + 1, hi, nums[hi]), res)
return res
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。