力扣剑指Offer 第25天模拟(中等)剑指 Offer 29. 顺时针打印矩阵 剑指 Offer 31. 栈的压入、弹出序列
剑指 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
题解
模拟
- 使用
turn记录当前行走方向 右 下 左 上 - 每次将对应方向所有可用的值放入数组中
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix.length==0)return new int[0];
int total=matrix[0].length*matrix.length;
int up=0,right=matrix[0].length-1,down=matrix.length-1,left=0;
int turn=0;//0 right,1 down,2 left,3 up
int[] list=new int[total];
int cnt=0;
while(cnt<total){
switch(turn){
case 0:
for(int c=left;c<=right;c++)
list[cnt++]=matrix[up][c];
up++;
break;
case 1:
for(int r=up;r<=down;r++)
list[cnt++]=matrix[r][right];
right--;
break;
case 2:
for(int c=right;c>=left;c--)
list[cnt++]=matrix[down][c];
down--;
break;
case 3:
for(int r=down;r>=up;r--)
list[cnt++]=matrix[r][left];
left++;
break;
}
turn=(turn+1)%4;
}
return list;
}
}
剑指 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 之前弹出。
提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed 是 popped 的排列。
题解
栈模拟
使用一个中间栈,每次判断将要入栈的元素是否符合出栈要求,符合则出栈,不符合则从中间栈中判断,如果栈顶符合出栈要求则出栈,不符合则入栈。
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
if(pushed.length==0)return true;
LinkedList<Integer>stack=new LinkedList<>();
int pPush=0,pPop=0;
while(true){
while(pPush<pushed.length&&pushed[pPush]==popped[pPop]){
pPush++;pPop++;
}
while(!stack.isEmpty()&&stack.peek()==popped[pPop]){
stack.pop();pPop++;
}
if(pPush<pushed.length)stack.push(pushed[pPush++]);
else break;
}
return pPop==popped.length?true:false;
}
}
这篇博客介绍了如何实现顺时针打印矩阵的算法,通过模拟行走方向来有序地获取矩阵元素。同时,探讨了如何判断给定的压入和弹出序列是否符合栈的操作逻辑,通过栈模拟来验证序列的正确性。
205

被折叠的 条评论
为什么被折叠?



