LeetCode-Python: Search in Rotated Sorted Array II
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:
|
|
允许重复元素,在判断的时候,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)。