[LeetCode] 81. Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
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).
Write a function to determine if a given target is in the array.
The array may contain duplicates.

Thought process:
The idea is similar to "154. Find Minimum in Rotated Sorted Array". If duplicates are allowed, worst case run-time will increase to O(n). Think about a case where the array contains a bunch of 1s and one 0, and we're searching for 0. 
We eliminate the edge case where nums[left] == nums[right] at the beginning of the while loop. After that, the code is similar to the question where duplicates are not allowed. Pay attention to those <= and >= signs, because they do matter in some edge cases.

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
35
36
37
38
39
public class Solution {
    public boolean search(int[] nums, int target) {
        if (nums.length == 0) {
            return false;
        }
        
        int left = 0;
        int right = nums.length - 1;
        int first = nums[0];
        
        while (left + 1 < right) {
            if (nums[left] == nums[right]) {
                right--;
                continue;
            }
            
            int mid = left + (right - left) / 2;
            if (nums[mid] >= first) {
                if (nums[mid] < target || first > target) {
                    left = mid;
                } else {
                    right = mid;
                }
            } else {
                if (nums[mid] > target || first <= target) {
                    right = mid;
                } else {
                    left = mid;
                }
            }
        }
        
        if (nums[left] == target || nums[right] == target) {
            return true;
        } else {
            return false;
        }
    }
}

Time complexity:
Average case O(logn). Worst case O(n).

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