《剑指Offer》-06查找与排序

旋转数组的最小数字

题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

方法一:顺序遍历

1
2
3
4
5
6
7
8
9
10
11
12
function minNumberInRotateArray(rotateArray)
{
// write code here
if(rotateArray.length===0){
return 0;
}
for(var i=0;i<rotateArray.length-1;i++){
if(rotateArray[i]>rotateArray[i+1]){
return rotateArray[i+1];
}
}
}

方法二:Sort排序

1
2
3
4
5
6
7
8
9
10
11
12
function minNumberInRotateArray(rotateArray)
{
// write code here
if(rotateArray.length===0){
return 0;
}
rotateArray.sort(function(a,b){
return a-b;
})
return rotateArray[0];

}

方法三:二分法查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function minNumberInRotateArray(rotateArray)
{
// write code here
if(rotateArray.length===0){
return 0;
}
var low=0,
high=rotateArray.length-1;
while(low<high){
var mid=low+Math.floor((high-low)/2);
if(rotateArray[mid]>rotateArray[high]){
low=mid+1;
}
else{
high=mid;
}
}
return rotateArray[low];
}

总结:
arr.sort(function(a,b){return a-b}) 升序
arr.sort(function(a,b){return b-a}) 降序
旋转之后的数组实际上可以划分为两个排序的子数组,而且前面的子数组的元素都大于或者等于后面的子数组的元素。最小的元素刚好是这两个子数组的分界线。在排序的数组中可以用二分查找实现O(logn)的查找。
旋转数组可分为两段渐变数列,通过mid与数组第一个和最后一个数进行比较,判断mid在哪个渐变序列中,再缩小搜索范围low和high,直到找到最小值。

0%