Matrix transpose that is simple enough to burst:
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int n=matrix[0].size();
int m=matrix.size();
vector<vector<int>> res(n,vector<int>(m));
int k=m*n;
for(int i=0;i<k;i++){
res[i%n][i/n]=matrix[i/n][i%n];
}
return res;
}
};
What you learn is nothing more than one
res[i%n][i/n]=matrix[i/n][i%n];
So keep it in mind. In this case, n represents the number of rows in the matrix. The number of rows after transposition is matrix[0].size().
The second question: https://leetcode-cn.com/problems/flipping-an-image/
is actually a simple batch, but maybe I have found the optimal solution, and I only need to traverse it once. If you are interested, be smart Still have
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
//相等则进行取反,否则不操作
int n=image.size();
int m=image[0].size();
int mm=m/2;
if(m%2==1) mm++;
for(int i=0;i<n;i++){
for(int j=0;j<mm;j++){
if(image[i][j]==image[i][m-1-j]){
image[i][j]=image[i][m-1-j]=image[i][j]^1;
}
}
}
return image;
}
};
The toothache was a bit terrible, and the wisdom teeth began to commotion again.