Problem: 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.

You may assume no duplicate exists in the array.

Solution: Find Minimum in Rotated Sorted Array, Python:

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
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-01-03 23:12:24
# @Author : NSSimacer
# @Version : 1.0
class Solution:
# @param num, a list of integer
# @return an integer
def findMin(self, num):
length = len(num)
if length == 0:
return 0
first = 0
last = length - 1
result = 0
while first <= last:
if num[first] <= num[last]:
result = num[first]
mid = first + (last - first) / 2
if num[mid] >= num[last]:
first = mid + 1
else:
last = mid
return result

二分搜索,时间复杂度为O(log n)。