Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
58 lines (45 loc) · 1.38 KB

File metadata and controls

58 lines (45 loc) · 1.38 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.ArrayList;
/**
* 剑指Offer,顺时针打印矩阵
*/
public class PrintMatrix {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4, 5}
};
ArrayList<Integer> list = printMatrix(matrix);
for (int i : list) {
System.out.print(i + " ");
}
}
public static ArrayList<Integer> printMatrix(int [][] matrix) {
if (matrix == null || matrix.length == 0) {
return null;
}
ArrayList<Integer> result = new ArrayList<>();
int up = 0, left = 0, down = matrix.length - 1, right = matrix[0].length - 1;
while (left <= right && up <= down) {
// 从左到右打印一行
for (int i = left; i <= right; i++) {
result.add(matrix[up][i]);
}
up++;
// 从上到下打印一列
for (int i = up; i <= down; i++) {
result.add(matrix[i][right]);
}
right--;
// 从右到左打印一行
for (int i = right; i >= left && up <= down; i--) {
result.add(matrix[down][i]);
}
down--;
// 从下到上打印一列
for (int i = down; i >= up && left <= right; i--) {
result.add(matrix[i][left]);
}
left++;
}
return result;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.