剑指 offer 第 25 天

2023-05-08,

第 25 天

模拟(中等)

剑指 Offer 29. 顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

题解思想:模拟

模拟:上下左右移动,同时判断边界是否相撞

class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return new int[0];
}
int left = 0;
int right = matrix[0].length - 1;
int high = 0;
int low = matrix.length - 1;
int temp = 0;
int[] res = new int[(right+1) * (low+1)];
while (true) {
for (int i = left; i <= right; i ++) {
res[temp] = matrix[high][i];
temp ++;
}
high ++;
if (high > low) {
break;
}
for (int i = high; i <= low; i ++) {
res[temp] = matrix[i][right];
temp ++;
}
right --;
if (right < left) {
break;
}
for (int i = right; i >= left; i --) {
res[temp] = matrix[low][i];
temp ++;
}
low --;
if (low < high) {
break;
}
for (int i = low; i >= high; i --) {
res[temp] = matrix[i][left];
temp ++;
}
left ++;
if (left > right) {
break;
}
}
return res;
}
}

复杂度:时间 O(nm) 空间 (1)

剑指 Offer 31. 栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。

示例 1:

输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

示例 2:

输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。

题解思想:模拟

模拟:使用一个栈进行模拟,遇到入栈序列则入栈,遇到出栈则出栈,最后判断栈是否为空

class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int i = 0;
for (int n : pushed) {
stack.push(n);
while (!stack.isEmpty() && stack.peek() == popped[i]) {
stack.pop();
i ++;
}
}
return stack.isEmpty();
} }

复杂度:时间 O(n) 空间 (n)

剑指 offer 第 25 天的相关教程结束。

《剑指 offer 第 25 天.doc》

下载本文的Word格式文档,以方便收藏与打印。