LeetCode刷题记录2
创建于
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 基本思路是二分查找,三个指针分别是首尾和中间
- 数组为空
- 数组只有一个值
- 形如[3,3,1,3]的数组,只能顺序查找(首尾和中间都是相等的)
class Solution {
public int minArray(int[] numbers) {
if(numbers==null){
return -1;
}
if(numbers.length==1){
return numbers[0];
}
int head=0,min;
int tail=numbers.length-1;
if(numbers[head]==numbers[tail]&&numbers[(head+tail)/2]==numbers[head]){
for(int i=1;i<tail;i++){
if(numbers[i-1]>numbers[i]){
return numbers[i];
}
}
}
while(head!=tail-1){
min=(head+tail)/2;
if(numbers[min]<=numbers[tail]){
tail=min;
continue;
}
if(numbers[head]<=numbers[min]){
head=min;
//continue;这个地方在末尾,有没有continue都一样
}
}
return tail==1?(Math.min(numbers[0], numbers[1])):numbers[tail];
}
}
```java