二维数组
# 48. 旋转图像 (opens new window)
class Solution {
public void rotate(int[][] matrix) {
int m = matrix.length;
for(int i=0;i<m;i++){
for(int j=i;j<m;j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for(int[] row:matrix){
reverseRow(row);
}
}
void reverseRow(int[] arr){
int i=0,j=arr.length-1;
while(i<j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;j--;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 54. 螺旋矩阵 (opens new window)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int l=0,r=n-1;
int u=0,b=m-1;
List<Integer> ret = new ArrayList<>();
while(ret.size()<m*n){
if(u<=b){
for(int i=l;i<=r;i++){
ret.add(matrix[u][i]);
}
u++;
}
if(l<=r){
for(int j=u;j<=b;j++){
ret.add(matrix[j][r]);
}
r--;
}
if(b>=u){
for(int i=r;i>=l;i--){
ret.add(matrix[b][i]);
}
b--;
}
if(r>=l){
for(int j=b;j>=u;j--){
ret.add(matrix[j][l]);
}
l++;
}
}
return ret;
}
}
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
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
# 73. 矩阵置零 (opens new window)
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean[] row = new boolean[m];
boolean[] col = new boolean[n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]==0){
row[i] = col[j] = true;
}
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(row[i] || col[j]){
matrix[i][j] = 0;
}
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 240. 搜索二维矩阵 II (opens new window)
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int i=0,j=n-1;
while(i<m && j>=0){
if(target==matrix[i][j]){
return true;
}else if(target<matrix[i][j]){
j--;
}else{
i++;
}
}
return false;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17