[LeetCode] 33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.

Thought process:
O(n) solution is trivial. I need to get O(logn) solution using binary search. When I cut the array in half, there are two cases:
  1. Middle < target: if the array is not rotated, I will keep the right half. However, currently there is a case where I need to keep the left half. That is when middle is from the rotated part of the array and target is larger than nums[0].
  2. Middle >= target: if the array is not rotated, I will keep the left half. However, there is a case where I need to keep the right half. That is when middle is from the part that's not rotated and target is less than nums[0].

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Solution {
    public int search(int[] nums, int target) {
        if (nums.length == 0) {
            return -1;
        }
        
        int left = 0;
        int right = nums.length - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                if (nums[mid] < nums[0] && target >= nums[0]) {
                    right = mid;
                } else {
                    left = mid;
                }
            } else {
                if (nums[mid] > nums[0] && target < nums[0]) {
                    left = mid;
                } else {
                    right = mid;
                }
            }
        }
        
        if (nums[left] == target) {
            return left;
        }
        if (nums[right] == target) {
            return right;
        }
        return -1;
    }
}

Time complexity: O(logn).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula