面试题 03.01. 三合一
分析
- 一个数组存元素,一个数组存指针,指针指向该栈最后一个元素对应索引的下一索引
- 数组栈中,三个连续的位置依顺序存第一二三栈的值
class TripleInOne {
int[] stack; //放栈中的元素
int[] index; //三个栈的指针
public TripleInOne(int stackSize) {
stack = new int[stackSize * 3]; //一个数组表示三个栈,故要三倍的长度。
//0、3、6...等表示第一个栈存储元素的位置,1、4、7...表示第二个栈,2、5、8...表示第三个栈
index = new int[3]; //存放三个栈的指针,当前指针指向stack数组中已存放元素的下一个位置
index[0] = 0; // 若index[0]=3,说明第0个栈中已经存放一个元素
index[1] = 1;
index[2] = 2;
}
public void push(int stackNum, int value) {
if (index[stackNum] < stack.length) {
stack[index[stackNum]] = value; //当前指针指向最后一个元素的后一个位置,所以先在该位置存入元素,再把指针右移一位
index[stackNum] += 3;
}
}
public int pop(int stackNum) {
if (isEmpty(stackNum)) return -1;
index[stackNum] -= 3; //先把指针向下移一位,指向最后存储元素的位置
return stack[index[stackNum]];
}
public int peek(int stackNum) {
if (isEmpty(stackNum)) return -1;
return stack[index[stackNum] - 3]; //指针不变,返回指针前一位的值
}
public boolean isEmpty(int stackNum) {
if (index[stackNum] == stackNum) //指针在该栈的首位置,说明栈中没有元素
return true;
return false;
}
}
面试题 03.06 动物收容所
class AnimalShelf {
Queue<int[]> queue;
public AnimalShelf() {
queue = new LinkedList<>();
}
public void enqueue(int[] animal) {
queue.offer(animal);
}
public int[] dequeueAny() {
if (queue.isEmpty())
return new int[]{-1, -1};
else return queue.poll(); //如果不为空,取出队列第一个元素
}
public int[] dequeueDog() {
if (queue.isEmpty())
return new int[]{-1, -1};
else {
for (int[] animal : queue) { //遍历队列中的每一个元素
if (animal[1] == 1) { //如果为狗,则从队列中删除该动物,并返回
queue.remove(animal);
return animal;
}
}
}
return new int[]{-1, -1};
}
public int[] dequeueCat() {
if (queue.isEmpty())
return new int[]{-1, -1};
else {
for (int[] animal : queue) {
if (animal[1] == 0) {
queue.remove(animal);
return animal;
}
}
}
return new int[]{-1, -1};
}
}
面试题 08.01 三步问题
分析
- 小孩一次可以上1阶、2阶或3阶;
- dp[n-1] 当走到 n-1 台阶时,只剩一种走法
- dp[n-2] 当走到 n-2 台阶时,只剩两种走法
- dp[n-3] 当走到 n-3 台阶时,只剩四种走法
- 故当走第4个台阶,1台阶到4台阶有三个台阶,有四种走法;2台阶到4台阶有两个台阶,有2种走法;3台阶到4台阶只有一个台阶,只有一种走法,依次类推
- 走到第n台阶是,上三种情况都可以到达。所以dp[n] = dp[n-1] + dp[n-2] + dp[n-3];
class Solution {
public int waysToStep(int n) {
if (n < 3) return n;
if (n == 3) return 4;
int a = 1;
int b = 2;
int c = 4;
for (int i = 0; i < n - 3; i++) {
int tempb = b;
int tempc = c;
c = (c + (b + a) % 1000000007) % 1000000007;
b = tempc;
a = tempb;
}
return c;
}
}