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.
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 = { 1, 3, 5 };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;elsehigh--;}return nums[low];}}
C++
#include <bits/stdc++.h>using namespace std;int findMin(vector<int> &nums){int low = 0, high = nums.size() - 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;elsehigh--;}return nums[low];}int main(){vector<int> arr = {1, 3, 5};cout << findMin(arr);return 0;}
No comments:
Post a Comment