您现在的位置是:主页 > news > 张掖网站建设推广/福州seo技术培训
张掖网站建设推广/福州seo技术培训
admin2025/6/10 6:20:28【news】
简介张掖网站建设推广,福州seo技术培训,广州中海工程建设总局网站,百度怎样做网站题目 三合一。描述如何只用一个数组来实现三个栈。 你应该实现push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum)方法。stackNum表示栈下标,value表示压入的值。 构造函数会传入一个stackSize参数,代表每个栈的大小。 示例 …
题目
三合一。描述如何只用一个数组来实现三个栈。
你应该实现push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum)方法。stackNum表示栈下标,value表示压入的值。
构造函数会传入一个stackSize参数,代表每个栈的大小。
示例
输入:
[“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
不压入元素。
输入:
[“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]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/three-in-one-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:二维数组模拟
1、二维数组 res 模拟三个栈
2、start数组存三个栈的开始指针
3、end数组存三个栈的结束指针
Java实现
class TripleInOne {int[][] res;int[] start;int[] end;public TripleInOne(int stackSize) {res = new int[3][stackSize];start = new int[3];end = new int[3];Arrays.fill(start, 0);Arrays.fill(end, 0);}public void push(int stackNum, int value) {if (start[stackNum] < res[stackNum].length) {res[stackNum][start[stackNum]++] = value;}}public int pop(int stackNum) {if (start[stackNum] > end[stackNum]) {return res[stackNum][--start[stackNum]];} else return -1;}public int peek(int stackNum) {if (start[stackNum] > end[stackNum]) return res[stackNum][start[stackNum] - 1];else return -1;}public boolean isEmpty(int stackNum) {if (start[stackNum] == end[stackNum]) return true;return false;}
}