81. Search in Rotated Sorted Array II
problem description
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6]
might become [2,5,6,0,0,1,2]
).
You are given a target value to search. If found in the array return true
, otherwise return false
.
Example 1:
Example 2:
Follow up:
This is a follow up problem to Search in Rotated Sorted Array, where
nums
may contain duplicates.Would this affect the run-time complexity? How and why?
algorithm thought
相比于Search in Rotated Sorted Array,这题在数组中加入了重复的数字,导致会出现一些问题。比如left和right是一样的数,甚至是,left和mid和right都是一样的数,这就不好区分两个区间。首先使用一个循环处理,如果left和right一样,将left++。这样就能去除所有边界一样的情况。除去之后,就和前面没有重复数组是一样的处理情况了
code
algorithm analysis
本来是二分查找的变体,时间复杂度应该是O(lgn),但是这里有个对left和right的预处理,最坏情况下,时间复杂度会到O(n)。
Last updated