列表

详情


面试题 03.01. 三合一

三合一。描述如何只用一个数组来实现三个栈。

你应该实现push(stackNum, value)pop(stackNum)isEmpty(stackNum)peek(stackNum)方法。stackNum表示栈下标,value表示压入的值。

构造函数会传入一个stackSize参数,代表每个栈的大小。

示例1:

 输入:
["TripleInOne", "push", "push", "pop", "pop", "pop", "isEmpty"]
[[1], [0, 1], [0, 2], [0], [0], [0], [0]]
 输出:
[null, null, null, 1, -1, -1, true]
说明:当栈为空时`pop, peek`返回-1,当栈满时`push`不压入元素。

示例2:

 输入:
["TripleInOne", "push", "push", "push", "pop", "pop", "pop", "peek"]
[[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]]
 输出:
[null, null, null, null, 2, 1, -1, -1]

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class TripleInOne { public: TripleInOne(int stackSize) { } void push(int stackNum, int value) { } int pop(int stackNum) { } int peek(int stackNum) { } bool isEmpty(int stackNum) { } }; /** * Your TripleInOne object will be instantiated and called as such: * TripleInOne* obj = new TripleInOne(stackSize); * obj->push(stackNum,value); * int param_2 = obj->pop(stackNum); * int param_3 = obj->peek(stackNum); * bool param_4 = obj->isEmpty(stackNum); */

golang 解法, 执行用时: 88 ms, 内存消耗: 10.7 MB, 提交时间: 2021-06-23 10:26:05

type TripleInOne struct {
    q [3][]int
    size int
}


func Constructor(stackSize int) TripleInOne {
    return TripleInOne{
        q: [3][]int{},
        size: stackSize,
    }
}


func (this *TripleInOne) Push(stackNum int, value int)  {
    if len(this.q[stackNum]) < this.size {
        this.q[stackNum] = append(this.q[stackNum], value)
    }
}


func (this *TripleInOne) Pop(stackNum int) int {
    l := len(this.q[stackNum])
    if l > 0 {
        t := this.q[stackNum][l-1]
        this.q[stackNum] = this.q[stackNum][:l-1]
        return t
    }
    return -1
}


func (this *TripleInOne) Peek(stackNum int) int {
    l := len(this.q[stackNum])
    if l > 0 {
        return this.q[stackNum][l-1]
    }
    return -1
}


func (this *TripleInOne) IsEmpty(stackNum int) bool {
    return len(this.q[stackNum]) == 0
}


/**
 * Your TripleInOne object will be instantiated and called as such:
 * obj := Constructor(stackSize);
 * obj.Push(stackNum,value);
 * param_2 := obj.Pop(stackNum);
 * param_3 := obj.Peek(stackNum);
 * param_4 := obj.IsEmpty(stackNum);
 */

上一题