1.48. 旋转图像 - 力扣(LeetCode)
、
旋转90度,先以对角线为轴进行交换,再以中间轴(中垂对角线)左右交换。
旋转图像就是行列转置,经过以对角线为轴的变换之后,行元素已经变成了列元素,但是我们会发现还没有达到顺时针旋转90度的效果,是因为这是逆序的,所以还需要将元素从左到右边进行反转。以对角线的中垂线为轴。
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
for(int i = 0; i < n; i++){
for(int j = 0; j < i; j++){
swap(matrix[i][j], matrix[j][i]);
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n / 2; j++){
swap(matrix[i][j], matrix[i][n - j - 1]);
}
}
}
};
2. 73. 矩阵置零 - 力扣(LeetCode)
nia886 不知道怎么标记呗
先遍历矩阵,遇到0的就把那一行那一列做个标记。
再次遍历矩阵只要做了标记的逐一化为0
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<int> row(m), col(n);
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == 0){
row[i] = true;
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;
}
}
}
}
};
3.289. 生命游戏 - 力扣(LeetCode)
哎哟 我去 我感觉就是考对代码掌握的熟练程度 我。。。
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int rows = board.size(), cols = board[0].size();
vector<vector<int>> temp(rows, vector<int>(cols, 0));
int neighbor[3] = {-1, 0, 1};
for(int = 0; row < rows; row++){
for(int col = 0; col < cols; col++){
temp[row][col] = board[row][col];
}
}
for(int row = 0; row < rows; row++){
for(int col = 0; col < cols; col++){
int liveNei = 0; //每次遍历一个细胞都要重新审视它身边的细胞
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(!(neighbor[i] && neighbor[j])){
int r = (row + neighbor[i]);
int c = (col + neighbor[j]);
if(r >= 0 && r < rows && c >= 0 && c < cols && temp[r][c] == 1){
liveNei += 1;
}
}
}
}
if(temp[row][col] == 1 && liveNei < 2 || liveNei > 3){
board[r][col] = 0;
}
if(temp[row][col] == 0 && liveNei == 3){
board[row][col] = 1;
}
}
}
}
};
4. 304. 二维区域和检索 - 矩阵不可变 - 力扣(LeetCode)
在b站学的那个方法太繁琐了还要额外判断第一行第一列,但是很好的帮助我去理解二维前缀和。
class NumMatrix {
vector<vector<int>> sum;
public:
NumMatrix(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
matrix.resize(m + 1, vector<int>(n + 1, 0));
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-][j-1];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sum[row2+1][col2+1] - sum[row2+1][col1] - sum[row1][col2+1] + sum[row1][col1];
}
};
aaaaaaaaaa 我发现我还是没有真正搞懂这个二维前缀和 我只能先死记一下。。。
5.238. 除自身以外数组的乘积 - 力扣(LeetCode)
从左往右,从右往左的前缀乘哈哈
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> res;
vector<int> L(n,0), R(n,0);
L[0] = 1;
for(int i = 0; i < n; i++){
L[i] = L[i-1] * nums[i];
}
R[n-1] = 1;
for(int i = n-2; i >= 0; i++){
R[i] = R[i+1] * nums[i+1];
}
for(int i = 0; i < n; i++){
res[i] = L[i] * R[i];
}
return res;
}
};