81. Search in Rotated Sorted Array II

Difficulty:
Related Topics:
Similar Questions:

Problem

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:

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:

Solution

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {boolean}
 */
var search = function(nums, target) {
  var left = 0;
  var right = nums.length - 1;
  var mid = 0;
  while (left <= right) {
    mid = Math.floor((left + right) / 2);
    if (nums[mid] === target) return true;
    if (nums[mid] > nums[left]) {
      if (nums[left] <= target && target < nums[mid]) {
        right = mid - 1;
      } else {
        left = mid + 1;
      }
    } else if (nums[mid] < nums[left]) {
      if (nums[mid] < target && target <= nums[right]) {
        left = mid + 1;
      } else {
        right = mid - 1;
      }
    } else {
      left++;
    }
  }
  return false;
};

Explain:

see Search in Rotated Sorted Array.

  1. 判断哪边是有序的
  2. 判断 target 在有序的那边还是无序的那边

注意重复数字的情况下,只能一个个移动,因为没法判断在哪边。这样算法最坏的情况就是 O(n) 了。

Complexity: