81. Search in Rotated Sorted Array II
# Medium
Solution 1:
Keep one of them when having repeated elements at the beginning and end of the list
Look for the pivot, which is to find the first pivot position. (In order to deal with two situations on time: it's an ascending list, it's a rotated list, always compare
mid
andleft
first which means keep the left side is an ascending list.)Do binary search according to above two situations
Consider the edge case: 0 element
[6,8,5,5,5] and [6,8,9,9,9]
[5,5,5,4] and [4,5,5,5]
When looking for the pivot, if value(mid) = value(left), keep right side
Judging the list is an ascending or rotated list according to comparison of nums[left]
and nums[right]
, then do binary search at the same time
Time complexity: Because we can't confirm time complexity of step1. The worst case is . Except that step, time complexisty =
Solution 2:
remove the repeated elements from start and end
find the pivot, consider three cases
search the target, consider three cases
Solutioin 3 (Java one-pass):
remove same element from end, such as [4, 4, 5, 1, 3, 4, 4] -> [4, 4, 5, 1, 3]
Same as #33, two cases: [start, end] is rotated; [start, end] is not rotated
Last updated
Was this helpful?