面试题 03.01. 三合一

题目

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

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

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

示例1:

1
2
3
4
5
6
输入:
["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:

1
2
3
4
5
输入:
["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

解法

解法一:

借助HashSet

遍历其中某一个链表,全放入HashSet中。然后遍历剩下一个链表,第一个在HashSet中出现的链表节点就是交点。

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
int[] index;
int stackSize;
int[] values;
public TripleInOne(int stackSize) {
values = new int[stackSize * 3];
index = new int[3];
this.stackSize = stackSize;
}

public void push(int stackNum, int value) {
if (index[stackNum] < stackSize) {
values[stackNum * stackSize + index[stackNum]++] = value;
}
}

public int pop(int stackNum) {
if (index[stackNum] <= 0) {
return -1;
}
return values[stackNum * stackSize + (--index[stackNum])];
}

public int peek(int stackNum) {
if (index[stackNum] <= 0) {
return -1;
}
return values[stackNum * stackSize + (index[stackNum] - 1)];
}

public boolean isEmpty(int stackNum) {
return index[stackNum] <= 0;
}
}

/**
* 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);
* boolean param_4 = obj.isEmpty(stackNum);
0%