Search in Rotated Sorted Array II

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 returntrue, otherwise returnfalse.

Example 1:

Input:
 nums = [2
,5,6,0,0,1,2]
, target = 0

Output:
 true

Example 2:

Input:
 nums = [2
,5,6,0,0,1,2]
, target = 3

Output:
 false

Follow up:

  • This is a follow up problem to Search in Rotated Sorted Array, wherenumsmay contain duplicates.

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

Analysis

这一题是Search in Rotated Sorted Array 的follow up,主要区别就是这里nums可能有重复元素。这样的话直接用原来的二分搜索就会有问题。这里需要注意的是如何处理重复元素。

同样是是先判断mid的左右区间是否为单调区间或者翻转区间,不同的是nums[mid]nums[right]可能相等,这种情况下的处理就是移动搜索区间右边界right(因为是nums[mid], nums[right]比较,如果是nums[mid], nums[left]比较,则需要移动区间左边界left)。

有一个预处理搜索边界start/end的方法:

Solution

Template #3 (compare nums[mid] vs nums[right]) - (1 ms, faster than 56.43%)

@hpplayer Template #1 (compare nums[mid] vs nums[left]) - ()

Template #1 with preprocessing of start, end

Last updated

Was this helpful?