题目
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
思路
public class Solution {
public static void main(String
[] args
) {
int[] arr
={3,4,5,1,2};
System
.out
.println(minArray(arr
));
}
public static int spinArray(int[] numbers
){
int minValue
= numbers
[numbers
.length
-1];
for (int i
= numbers
.length
-2; i
>= 0 ; i
--){
if (minValue
> numbers
[i
]){
minValue
= numbers
[i
];
}
}
return minValue
;
}
}
public class Solution {
public static void main(String
[] args
) {
int[] arr
={3,4,5,1,2};
System
.out
.println(minArray(arr
));
}
public static int minArray(int[] numbers
){
return spinArray(numbers
,0,numbers
.length
-1);
}
public static int spinArray(int[] array
,int left
, int right
){
int mid
= (left
+ right
) / 2;
if (left
>= right
){
return array
[left
];
}
if(array
[mid
] > array
[right
]){
return spinArray(array
,mid
+1,right
);
}else if(array
[mid
] < array
[right
]) {
return spinArray(array
, left
, mid
);
}else {
return spinArray(array
, left
, right
- 1);
}
}
}
public class Solution {
public static void main(String
[] args
) {
int[] arr
={3,4,5,1,2};
System
.out
.println(minArray(arr
));
}
public static int minArray(int[] numbers
){
int left
= 0;
int right
= numbers
.length
- 1;
while (left
< right
){
int mid
= (left
+ right
) / 2;
if (numbers
[mid
] > numbers
[right
]){
left
= mid
+ 1;
}else if (numbers
[mid
] < numbers
[right
]){
right
= mid
;
}else{
right
--;
}
}
return numbers
[left
];
}
}