Problem: Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

Solution: Search in Rotated Sorted Array II, 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
53
54
55
56
#!/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
# @return a boolean
def search(self, A, target):
if len(A) == 0:
return False
first = 0
last = len(A)
while first != last:
mid = (first + last) / 2
if A[mid] == target:
return True
if A[first] < A[mid]:
if A[first] <= target and target < A[mid]:
last = mid
else:
first = mid + 1
elif A[first] > A[mid]:
if A[mid] < target and target <= A[last - 1]:
first = mid + 1
else:
last = mid
else:
first += 1 # skip duplicate one
return False

允许重复元素,在判断的时候,A[first] <= A[mid],区间[first, mid]的元素不能保证是递增序列,比如[1, 3, 1, 1, 1]。

可以考虑把这个判断条件拆分成两部分:

若A[mid] > A[first]: 区间[first, mid]元素一定递增

若A[mid] == A[first]: 无法判断序列是否递增,将first自增,即向前看一个元素

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