73. 矩阵置零
class Solution {
public:
void setZeroes(vector<vector<int>>& a) {
int n = a.size(), m = a[0].size();
vector<int> r(n + 10, 0);
vector<int> c(m + 10, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!a[i][j]) {
r[i] = 1;
c[j] = 1;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (r[i] || c[j]) a[i][j] = 0;
}
}
}
};
模拟
54. 螺旋矩阵
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& a) {
int n = a.size(), m = a[0].size();
int x = 0, y = 0;
int sum = m * n;
int sx = n - 1, sy = m;
int dx = 1, dy = 1;
vector<int> ans;
while (sum) {
for (int i = 1; i <= sy; i++) {
ans.push_back(a[x][y]);
y += dy;
sum--;
}
dy *= -1;
sy--;
x += dx;
y += dy;
for (int i = 1; i <= sx; i++) {
ans.push_back(a[x][y]);
x += dx;
sum--;
}
dx *= -1;
sx--;
y += dy;
x += dx;
}
return ans;
}
};
套路题,模拟
48. 旋转图像
class Solution {
public:
void rotate(vector<vector<int>>& a) {
int n = a.size(), m = a[0].size();
vector<vector<int>> ans(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ans[j][n - i - 1] = a[i][j];
}
}
swap(a, ans);
}
};
套路题,模拟
240. 搜索二维矩阵 II
class Solution {
public:
bool searchMatrix(vector<vector<int>>& a, int target) {
int n = a.size(), m = a[0].size();
int x = 0, y = m - 1;
while (x < n && y >= 0) {
if (a[x][y] == target) return true;
if (a[x][y] > target) y--;
else x++;
}
return false;
}
};
Z字形查找