The topic is as follows
Moving several elements from the beginning of an array to the end of the array is called the rotation of the array. Input a rotation of an ascendingly sorted 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.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Own algorithm and code
(The code can be run and submitted correctly) The
specific algorithm is as follows:
- Initialize the minimum value
min=-1
; - Through the array, if satisfied
numbers[i] > numbers[i+1]
, will benumbers[i+1]
assigned tomin
, and out of the loop; - Determining
min
whether or not equal to the initial value-1
, i.e., whether the array satisfyingnumbers[i] > numbers[i+1]
conditions; - If
min==-1
, there may be two situations: the minimum is the first or the last, so compare the two numbers;- If
numbers[0] < numbers[numbers.length-1]
, thenmin = numbers[0]
; - If
numbers[0] > numbers[numbers.length-1]
, thenmin = numbers[numbers.length-1]
;
- If
public class Solution {
public static int minArray(int[] numbers) {
int min = -1;
for (int i = 0; i < numbers.length-1; i++){
if (numbers[i] > numbers[i+1]){
min = numbers[i+1];
break;
}
}
if (min == -1){
if (numbers[0] < numbers[numbers.length-1]){
min = numbers[0];
}else {
min = numbers[numbers.length-1];
}
}
return min;
}
public static void main(String[] args) {
int[] numbers = {
2,3,4,5,1};
int result = minArray(numbers);
System.out.println(result);
}
}
Reference algorithm and code (binary search method)
class Solution {
public int minArray(int[] numbers) {
int low = 0;
int high = numbers.length - 1;
while (low < high) {
int middle = low + (high - low) / 2;
if (numbers[middle] < numbers[high]) {
high = middle ;
} else if (numbers[middle] > numbers[high]) {
low = middle + 1;
} else {
high -= 1;
}
}
return numbers[low];
}
}