Sunday, June 26, 2022

[LeetCode] Search in Rotated Sorted Array II

Problem: There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).

Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].

Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.

You must decrease the overall operation steps as much as possible.

Example:

Input: nums = [1,0,1,1,1], target = 0
Output: true
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false


Approach: This question is similar to search an element is sorted rotated array but here the elements in the array might not be distinct. We will apply the same approach here with little modification to avoid duplicate values. You can look at the implementation to understand the extra step.


Implementation in C#:

    public bool Search(int[] nums, int target) 

    {

        int length = nums?.Length ?? 0;

        if (length == 0)

        {

            return false;

        }

        int start = 0, end = length - 1;

        while (start <= end && nums[start] == nums[end])

        {

            if (nums[start] == target)

            {

                return true;

            }

            ++start;

            --end;

        }  

        while (start <= end)

        {

            int mid = start + (end - start) / 2;            

            if (target == nums[mid]) 

            {

                return true;

            }     

            if (nums[start] <= nums[mid])

            {

                if (target >= nums[start] && target < nums[mid])

                {

                    end = mid - 1;

                }

                else

                {

                    start = mid + 1;

                }

            }

            else

            {

                if (target > nums[mid] && target <= nums[end])

                {

                    start = mid + 1;

                }

                else

                {

                    end = mid - 1;

                }

            }

        }        

        return false;

    }


Complexity: O(n)

No comments:

Post a Comment