54. 螺旋矩阵
class Solution {
public:vector<int> spiralOrder(vector<vector<int>>& matrix) {vector<int> vec;if(matrix.empty())return vec;int left=0;int right = matrix[0].size()-1;int up=0;int down = matrix.size()-1;while(true) {for(int i=left;i<=right;++i) {vec.push_back(matrix[up][i]);}up++;if(up>down) break;for(int i=up;i<=down;i++) {vec.push_back(matrix[i][right]);}right--;if(right<left) break;for(int i=right;i>=left;i--) {vec.push_back(matrix[down][i]);}down--;if(down<up) break;for(int i=down;i>=up;i--) {vec.push_back(matrix[i][left]);}left++;if(left>right) break;}return vec;}
};
73. 矩阵置零
class Solution {
public:void setZeroes(vector<vector<int>>& matrix) {int flag0 = 1;for(int i=0 ; i<matrix.size();i++) {if(matrix[i][0]==0)flag0=0;}for(int i=0;i<matrix.size();i++) {for(int j=0;j<matrix[0].size();j++) {if(matrix[i][j]==0)matrix[i][0]=0;}}for(int j=1;j<matrix[0].size();j++) {for(int i=0;i<matrix.size();i++) {if(matrix[i][j]==0) {for(int i=0;i<matrix.size();i++) {matrix[i][j]=0;}break;}elsecontinue;}}for(int i=0;i<matrix.size();i++) {if(matrix[i][0]==0) {for(int j=0;j<matrix[0].size();j++) {matrix[i][j]=0;}continue;}}if(flag0==0) {for(int i=0;i<matrix.size();i++) {matrix[i][0]=0;}}}
};
48. 旋转图像
思路:
黑色圈住的区域是遍历范围(划分 n为奇数和偶数两种情况),其中的每个点下标(按照大致的逻辑:旋转第i行转90°变成倒数第i列 )找到旋转90、180、270、的对应下标,只需要一个变量temp暂存matrix[i][j],然后交替替换值
class Solution {
public:void rotate(vector<vector<int>>& matrix) {if(matrix.size() <=1)return;int n = matrix.size();if(n%2 ==0) {for(int i=0;i<n/2;i++) {for(int j=0;j<n/2;j++) {int a = matrix[i][j];matrix[i][j] = matrix[n-j-1][i];matrix[n-j-1][i] = matrix[n-1-i][n-1-j];matrix[n-1-i][n-1-j] = matrix[j][n-1-i];matrix[j][n-i-1] = a;}}}if(n%2 ==1) {for(int i=0;i<n/2;i++) {for(int j=0;j<n/2+1;j++) {int a = matrix[i][j];matrix[i][j] = matrix[n-j-1][i];matrix[n-1-j][i] = matrix[n-1-i][n-1-j];matrix[n-1-i][n-1-j] = matrix[j][n-1-i];matrix[j][n-i-1] = a;}}}}
};
还有一个题目明天继续