Find Minimum in Rotated Sorted Array II

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
Find the minimum element.
The array may contain duplicates.

Example 1:

Input: arr=[1,3,5]
Output: 1

Approach

Java

public class FindMiniRotated {
    public static void main(String[] args) {
        int[] arr = { 135 };
        System.out.println(findMin(arr));
    }

    static int findMin(int[] nums) {
        int low = 0, high = nums.length - 1, mid = 0;
        while (low < high) {
            mid = low + (high - low) / 2;
            if (nums[mid] > nums[high])
                low = mid + 1;
            else if (nums[mid] < nums[high])
                high = mid;
            else
                high--;
        }
        return nums[low];
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int findMin(vector<int&nums)
{
    int low = 0high = nums.size() - 1mid = 0;
    while (low < high)
    {
        mid = low + (high - low) / 2;
        if (nums[mid] > nums[high])
            low = mid + 1;
        else if (nums[mid] < nums[high])
            high = mid;
        else
            high--;
    }
    return nums[low];
}

int main()
{
    vector<intarr = {1, 3, 5};
    cout << findMin(arr);
    return 0;
}


No comments:

Post a Comment