Suppose an array of length
Notice that rotating an array
Given the sorted rotated array
n
sorted in ascending order is rotated between 1
and n
times. Notice that rotating an array
[a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.Given the sorted rotated array
nums
, return the minimum element of this array.Example 1:
Input: nums = [3,4,5,1,2] Output: 1
Approach
Java
public class FindMinRotatedArray {public static void main(String[] args) {int[] nums = {3,4,5,1,2 };System.out.println(findMin(nums));}static int findMin(int[] nums) {if (nums.length == 1)return nums[0];int low = 0, high = nums.length - 1;if (nums[high] > nums[0])return nums[0];while (low <= high) {int mid = low + (high - low) / 2;if (nums[mid] > nums[mid + 1])return nums[mid + 1];else if (nums[mid - 1] > nums[mid])return nums[mid];if (nums[mid] > nums[0])low = mid + 1;if (nums[mid] < nums[0])high = mid - 1;}return -1;}}
C++
#include <bits/stdc++.h>using namespace std;int findMin(vector<int> &nums){if (nums.size() == 1)return nums[0];int low = 0, high = nums.size() - 1;if (nums[high] > nums[0])return nums[0];while (low <= high){int mid = low + (high - low) / 2;if (nums[mid] > nums[mid + 1])return nums[mid + 1];else if (nums[mid - 1] > nums[mid])return nums[mid];if (nums[mid] > nums[0])low = mid + 1;if (nums[mid] < nums[0])high = mid - 1;}return -1;}int main(){vector<int> nums = {3, 4, 5, 1, 2};cout << findMin(nums);return 0;}
No comments:
Post a Comment