描述
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.
基本设定和上一题一样,但允许重复元素。
另外,本题只需要输出True
or False
即可,不需要输出下标。
分析
允许重复元素之后,A[mid]
和A[low]
就有可能相等,这种情况下我们就无法判断A[mid]
是在哪个子数组中,这种情况下,我们可以简单地让low
指针向前走一步。这样一来,算法最坏情况下时间复杂度增加到了O(n),平均情况下仍然为O(log(n))。
代码
Python
1 | class Solution: |