81. Search in Rotated Sorted Array II

# Medium

Solution 1:

  1. Keep one of them when having repeated elements at the beginning and end of the list

  2. 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 and left first which means keep the left side is an ascending list.)

  3. Do binary search according to above two situations

  4. Consider the edge case: 0 element

triangle-exclamation
while left + 1 < right:
    mid = left + (right - left)//2
    if nums[mid] >= nums[left]:
        left = mid
    else:
        right = mid
pivot = right
circle-check

Time complexity: Because we can't confirm time complexity of step1. The worst case is T=O(n)T=O(n) . Except that step, time complexisty = O(lgN)O(lgN)

Solution 2:

  1. remove the repeated elements from start and end

  2. find the pivot, consider three cases

  3. search the target, consider three cases

Solutioin 3 (Java one-pass):

  1. remove same element from end, such as [4, 4, 5, 1, 3, 4, 4] -> [4, 4, 5, 1, 3]

  2. Same as #33, two cases: [start, end] is rotated; [start, end] is not rotated

Last updated