Suppose a rotated sorted array whose starting position is unknown (e.g. 0 1 2 4 5 6 7 May become 4 56 7 0 1 2).
You need to find the smallest of these elements.
You can assume that there are no duplicate elements in the array.
Idea: Dichotomy method
1, judge whether the smallest number is in the first position, if it returns NUMS[0];
2, otherwise, select the middle position mid and the number of R position to compare, if NUMS[MID] < Nums[r], indicating the smallest number in Mid, R = Mid; Conversely, make L = mid+1;
3, repeat, until L >= R.
public class Solution {
/*
* @param nums:a rotated sorted array
* @return: The minimum number in the array
*/
public int findmin (int[] nums) {
Write your code here
int l = 0;
int r = nums.length-1;
if (Nums[l] < Nums[r]) {
return nums[l];
}
while (L < R) {
int mid = (l+r)/2;
if (Nums[mid] > Nums[r]) {
L = mid + 1;
}else{
R = Mid;
}
}
return nums[l];
}
}
Find the smallest value in the rotated sorted array