[路飞]面试题 03.05. 栈排序

171 阅读2分钟

前言

栈是一种类似于数组的数据结构,是能在添加或者删除元素时进行更多控制的数据结构。 栈是一种遵从后进先出(LIFO)原则的有序集合。新添加或者待删除的元素都保存在栈的同一端,称作栈顶,另一端就叫栈底。

栈排序

题目描述

栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:push、pop、peek 和 isEmpty。当栈为空时,peek 返回 -1。

示例1:

输入: ["SortedStack", "push", "push", "peek", "pop", "peek"] [[], [1], [2], [], [], []]
输出:
[null,null,null,1,null,2]

示例2:

输入: ["SortedStack", "pop", "pop", "push", "pop", "isEmpty"] [[], [], [], [1], [], []]
输出: [null,null,null,null,null,true]

解题思路

定义一种性质,维护这种性质

  • 创建一个类来表示栈。
  • push(element(val)):添加一个(或几个)新元素到栈顶。(按照栈的性质是需要添加到栈顶的,但是按照题意,需要对新添加的元素做排序,把最小的元素放到栈顶)
  • pop():移除栈顶的元素,同时返回被移除的元素。
  • peek():返回栈顶的元素,不对栈做任何修改(该方法不会移除栈顶元素,仅仅返回它)
  • isEmpty():如果栈里没有任何元素就返回true,否则返回false。

代码

var SortedStack = function() {
    this.items = [];
};

/** 
 * @param {number} val
 * @return {void}
 */
 /**
 *push需要对新加入的数据做排序,把最小的元素放在栈顶
 *1.第一次push的时候,走步骤[2]
 *2.第n次push的时候,值为val = 4,假设items = [9, 6, 2, 1];
 *3.此时进入push方法,index = 0,进入步骤[1],index = 2;
 *4.然后进入步骤[3],反向遍历,大于index的值,都往后挪一位
 *5.最后执行this.items[index] = val;
 */
SortedStack.prototype.push = function(val) {
    let index = 0;
    for(var i = 0;i<this.items.length;i++){
        if(this.items[i] < val){ // [1]
            index = i;
            break;
        }else{
            index = this.items.length;
        }
    }
    if(index >= this.items.length){
        this.items.push(val) // [2]
    } else{
        for(j = this.items.length; j > index; j--){ // [3]
            this.items[j] = this.items[j - 1];
        }
        this.items[index] = val;
    }
};

/**
 * @return {void}
 */
SortedStack.prototype.pop = function() {
    return this.items.pop();
};

/**
 * @return {number}
 */
SortedStack.prototype.peek = function() {
    return this.items[this.items.length -1] === undefined ? -1 : this.items[this.items.length -1];
};

/**
 * @return {boolean}
 */
SortedStack.prototype.isEmpty = function() {
    return this.items.length === 0;
};

/**
 * Your SortedStack object will be instantiated and called as such:
 * var obj = new SortedStack()
 * obj.push(val)
 * obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.isEmpty()
 */