Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一、题目描述:
题目来源:LeetCode-三合一
三合一。描述如何只用一个数组来实现三个栈。
你应该实现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]
提示:
0 <= stackNum <= 2
二、思路分析:
思路一: 题目只要求我们使用「一个数组」来实现栈,并没有限制我们使用数组的维度。
因此一个简单的做法是,建立一个二维数组 datadata 来做。
二维数组的每一行代表一个栈,同时使用一个 locationslocations 记录每个栈「待插入」的下标。
思路二:
使用一维数组求解
建立一个长度为 3 * stackSize 的数组,并将 3 个栈的「待插入」存储在 locations数组。
三、AC 代码:
思路一:
class TripleInOne {
int n = 3;
int[][] data;
int[] locationsArray;
public TripleInOne(int stackSize) {
data = new int[n][stackSize];
locationsArray = new int[n];
}
public void push(int stackNum, int value) {
int[] stackArray = data[stackNum];
int locathionIndex = locationsArray[stackNum];
if (locathionIndex < stackArray.length) {
stackArray[locathionIndex] = value;
locationsArray[stackNum]++;
}
}
public int pop(int stackNum) {
int[] stk = data[stackNum];
int locationIndex = locationsArray[stackNum];
if (locationIndex > 0) {
int val = stk[locationIndex - 1];
locationsArray[stackNum]--;
return val;
} else {
return -1;
}
}
public int peek(int stackNum) {
int[] stack = data[stackNum];
int locationIndex = locationsArray[stackNum];
if (locationIndex > 0) {
return stack[locationIndex - 1];
} else {
return -1;
}
}
public boolean isEmpty(int stackNum) {
return locationsArray[stackNum] == 0;
}
}
时间复杂度:O(1)
思路二:
class TripleInOne {
int n = 3;
int[] data;
int[] locationsArray;
int stckSize;
public TripleInOne(int stackSize) {
stckSize = stackSize;
data = new int[stckSize * n];
locationsArray = new int[n];
for (int i = 0; i < n; i++) {
locationsArray[i] = i * stckSize;
}
}
public void push(int stackNum, int value) {
int index = locationsArray[stackNum];
if (index < (stackNum + 1) * stckSize) {
data[index] = value;
locationsArray[stackNum]++;
}
}
public int pop(int stackNum) {
int index = locationsArray[stackNum];
if (index > stackNum * stckSize) {
locationsArray[stackNum]--;
return data[index - 1];
} else {
return -1;
}
}
public int peek(int stackNum) {
int index = locationsArray[stackNum];
if (index > stackNum * stckSize) {
return data[index - 1];
} else {
return -1;
}
}
public boolean isEmpty(int stackNum) {
return locationsArray[stackNum] == stackNum * stckSize;
}
}
时间复杂度:O(1)。