第一题:剑指 Offer 29. 顺时针打印矩阵
问题描述
思路
按照从左到右,从上到下,从右到左,从下到上进行输入数组;
代码
public class Solution {
public int[] spiralOrder(int[][] matrix) {
int row = matrix.length;
if (row == 0) {
return new int[0];
}
int col = matrix[0].length;
int[] res = new int[row * col];
int idx = 0,i;
int left = 0, top = 0, right = col - 1, bottom = row - 1;
while (true) {
for ( i = left; i <= right; i++) {
res[idx++] = matrix[top][i];
}
if (++top > bottom) break;
//从上往下走
for ( i = top; i <= bottom; i++) {
res[idx++] = matrix[i][right];
}
if (--right < left) break;
//从右往左走
for ( i = right; i >= left; i--) {
res[idx++] = matrix[bottom][i];
}
if (--bottom < top) break;
//从下往上走
for ( i = bottom; i >= top; i--) {
res[idx++] = matrix[i][left];
}
if (++left > right) break;
}
return res;
}
}
时间空间复杂度
第二题:剑指 Offer 31. 栈的压入、弹出序列
问题描述
思路
代码
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int p1=0,p2=0;
for(int i=0;i<pushed.length;i++){
pushed[p1] = pushed[i];
while(p1 >= 0 && popped[p2] == pushed[p1]){
p1--;
p2++;
}
p1++;
}
return p1==0;
}
}