topic
Moving several elements from the beginning of an array to the end of the array is called array rotation. Input a rotation of an ascending array, and output the smallest element of the rotated array. For example, the array [3,4,5,1,2] is a rotation of [1,2,3,4,5], and the minimum value of the array is 1. link
Ideas
Two points, just note that the rotation point needs to be judged.
If num[mid]>num[right]
it means that the rotation point must be in mid
the [mid+1,right]
closed interval on the right
Because if the rotation point is on the
mid
left,mid
itright
must be in ascending order and cannot appearnum[mid]>num[right]
Otherwise, the rotation point is in the [left,mid]
closed interval.
class Solution {
public int minArray(int[] numbers) {
int left = 0, right = numbers.length - 1;
while(left < right){
int mid = left + (right - left) / 2;
if(numbers[mid] > numbers[right])
left = mid + 1;
else if(numbers[mid] < numbers[right])
right = mid;
else right--;
}
return numbers[left];
}
}