题目描述:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
题解:
- 方法一:利用数组的reduce方法,找出数组中的最小值。
function minNumberInRotateArray(rotateArray)
{
// write code here
return rotateArray.reduce(function(pre,cur){
return Math.min(pre,cur);
})
}
不用reduce数组也可以直接找出最小值。
function minNumberInRotateArray(rotateArray) {
const length = rotateArray.length;
if (!length) {
return 0;
}
return Math.min(...rotateArray);
}
- 方法二:对数组进行排序,数组的第一个即为最小值。
function minNumberInRotateArray(rotateArray)
{
// write code here
if(rotateArray.length == 0){
return 0;
}else{
let newArr = rotateArray.sort(function(a,b){return a-b;});
return newArr[0];
}
}
-
方法三:二分查找。
分析:二分查找变种,没有具体的值用来比较。那么用中间值和高低位进行比较,看处于递增还是递减序列,进行操作缩小范围。处于递增:low上移
处于递减:high下移(如果是high-1,则可能会错过最小值,因为找的就是最小值)
其余情况:low++缩小范围
function minNumberInRotateArray(rotateArray)
{
// write code here
var len = rotateArray.length;
if(len == 0){
return 0;
}
let low = 0;
let high = len-1;
while(low<high){
let mid = Math.floor((low+high)/2);
if(rotateArray[low] < rotateArray[high]){
return rotateArray[low];
}
if(rotateArray[low]<rotateArray[mid]){
low = mid + 1;
}else if(rotateArray[mid]<rotateArray[high]){
high = mid;
}else{
low++;
}
}
return rotateArray[low];
}
module.exports = {
minNumberInRotateArray : minNumberInRotateArray
};