LeetCode 54 - Spiral Order

这道题,触及我很多伤痛。高中OI,大学ACM,面试,今天终于完整写完了。。。

上下左右搭建4面墙,作为哨兵条件。每跳出一边,墙就向中间移动一次。记得每次都确认是否墙越界了。

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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if (matrix.length == 0)
return list;
int up = 0, down = matrix.length - 1, left = 0, right = matrix[0].length - 1;
int i = left;

while (up <= down) {
i = left;
while (i < right + 1) {
list.add(matrix[up][i++]);
}
i = up + 1;
up++;
if (up > down)
break;
while (i < down + 1) {
list.add(matrix[i++][right]);
}
i = right - 1;
right--;
if (left > right)
break;
while (i >= left) {
list.add(matrix[down][i--]);
}
i = down - 1;
down--;
if (up > down)
break;

while (i >= up) {
list.add(matrix[i--][left]);
}
left++;
if (left > right)
break;
}
return list;
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×