leetcode-spiral-matrix-i-ii

Posted petewell

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-spiral-matrix-i-ii相关的知识,希望对你有一定的参考价值。

原文引用https://www.dazhuanlan.com/2019/08/26/5d62fafb4de84/


题目大意

  https://leetcode.com/problems/spiral-matrix/

  https://leetcode.com/problems/spiral-matrix-ii/

  这两个题目本质上是一道题,都是螺旋式或者生成打印矩阵

题目分析

  最开始我的实现还是每行或者每列少打印一个,留给下一列或者下一行处理,这样导致最后还要特殊判断到底是剩下1行/列,或者是两行/列。导致代码极其不优雅,虽然可以AC。我觉得刷leetcode目标不仅仅是AC,更要追求时间/空间复杂度,以及代码的优雅。看了disscuss区的高票答案,就是简单的每次“缩减”行或者列就可以很优雅的解出来。至于Spiral Matrix II反而更简单,题目要求的是生成螺旋正方形,可以几乎完全复用代码即可。

代码

  Spiral Matrix:

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
42
43
44
45
public class
public List<Integer> spiralOrder(int[][] matrix)
List<Integer> ans = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return ans;
int m = matrix.length;
int n = matrix[0].length;
int up = 0;
int down = m - 1;
int left = 0;
int right = n - 1;
while (true)
for (int col = left; col <= right; col++)
ans.add(matrix[up][col]);
up++;
if (up > down)
break;
for (int row = up; row <= down; row++)
ans.add(matrix[row][right]);
right--;
if (right < left)
break;
for (int col = right; col >= left; col--)
ans.add(matrix[down][col]);
down--;
if (down < up)
break;
for (int row = down; row >= up; row--)
ans.add(matrix[row][left]);
left++;
if (left > right)
break;
return ans;

  Spiral Matrix II:

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
public class Solution
public int[][] generateMatrix(int n)
int[][] matrix = new int[n][n];
int up = 0;
int down = n - 1;
int left = 0;
int right = n - 1;
int c = 0;
while (true)
for (int col = left; col <= right; col++)
matrix[up][col] = ++c;
up++;
if (up > down)
break;
for (int row = up; row <= down; row++)
matrix[row][right] = ++c;
right--;
if (right < left)
break;
for (int col = right; col >= left; col--)
matrix[down][col] = ++c;
down--;
if (down < up)
break;
for (int row = down; row >= up; row--)
matrix[row][left] = ++c;
left++;
if (left > right)
break;
return matrix;

以上是关于leetcode-spiral-matrix-i-ii的主要内容,如果未能解决你的问题,请参考以下文章