旋转数组的最小数字

剑指offer-牛客网

Posted by Y. on October 25, 2018

旋转数组的最小数字

题目描述

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

思路

两个stack,push函数直接使用instack;pop时,考虑outstack是否为空,不为空,直接pop,为空,将instack全部push进outstack

代码

var inStack = [];
var outStack = [];

function push(node)
{
    // write code here
    inStack.push(node);
}
function pop()
{
    // write code here
    if(outStack.length == 0){
        if(inStack.length == 0){
            return null;
        }else{
            outStack = [];
            while(inStack.length != 0) {
                outStack.push(inStack.pop());
            }
        }
        return outStack.pop();
    }else {
        return outStack.pop();
    }
}

运行时间:21ms
占用内存: 5240k

最佳代码

var stack1 = [];
function push(node)
{
    // write code here
    stack1.push(node);
}
function pop()
{
    // write code here
    if(stack1.length == 0)
        return false;
    return stack1.shift();
}
  • 直接使用shift()函数