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).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Solution: Search 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
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-01-01 22:37:45
# @Author : NSSimacer
# @Version : 1.0
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
if len(A) == 0:
return -1
first = 0
last = len(A)
while first != last:
mid = (first + last) / 2
if target == A[mid]:
return mid
if A[first] <= A[mid]:
if A[first] <= target and target < A[mid]:
last = mid
else:
first = mid + 1
else:
if A[mid] < target and target <= A[last - 1]:
first = mid + 1
else:
last = mid
return -1

二分查找,难度主要在于左右边界的确定。

时间复杂度O(log n),空间复杂度O(1)。