LintCode Q159 Find Minimum in Rotated Sorted Array in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年12月29日
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
30
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
# time complexity: O(log(n))
# invalide input
if len(nums) == 0:
return
lo, hi = 0, len(nums) - 1
# sorted array
if nums[lo] < nums[hi]:
return nums[lo]
# rotated sorted array
[left, right] = [-1, -1]
while lo <= hi:
mid = lo + (hi - lo)/2
if mid < len(nums) - 1 and nums[mid] > nums[mid + 1]:
[left, right] = [mid, mid + 1]
break
elif mid > 0 and nums[mid - 1] > nums[mid]:
[left, right] = [mid - 1, mid]
break
elif nums[mid] < nums[len(nums)-1]:
hi = mid - 1
elif nums[mid] > nums[0]:
lo = mid + 1
else: # when len(nums) == 1
return nums[mid]
return nums[right]
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。