题目链接
06.01.01 练习题目(第 01 天)
笔记:
.
遍历方法:
1.走一行删一行,走一列删一列
int rows=m matrix.size();int cols= matrix[0].size();
int num=0;
int left=0;int up=0;int down=rows;int right=cols;
while(1){
for(int i=left;i<right;i++) ans[num++]= matrix[up][i];
if(++up<down-1)break;
for(int i=up;i<down;i++) ans[num++]= matrix[right][i];
if(--right>left)break;
for(int i=right;i>=left;i--) matrix[down][i]=num++;
if(--down<up) break;
for(int i=down;i>=up;i--) matrix[i][left]=num++;
if(++left>right)break;
}
2.模拟
directions[4][2]
class Solution {
private:
static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
//{0,1} 向右走,{1,0},向下走,{0,-1}向左走,{-1,0}向上走
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
if (n == 0)
return matrix;
int num = 1;
vector<vector<bool>> visited(n, vector<bool>(n));
int row = 0;int col = 0; //遍历使用
int rows = n; int cols = n;
int index = 0;
while (num <= n * n) {
visited[row][col] = true;
//对 matrix[row][col]执行操作
int nextrow = row + directions[index][0];
int nextcol = col + directions[index][1];
if (nextrow >= n || nextcol >= n || nextrow < 0 || nextcol < 0 ||
visited[nextrow][nextcol])
index = (index + 1) % 4;
row = row + directions[index][0];
col = col + directions[index][1];
}
return matrix;
}
};
二、旋转图像
swap(ans[i][j],ans[n][m]);
矩阵的旋转,可以考虑对角线,或者找规律。
行互换时,只需要换半个行,列全换;(for)
for(int i=0;i<n/2;i++)
for(int j=0;j<n;j++)
swap(matrix[i][j], matrix[n - i - 1][j]);
主对角线互换时,换斜着的一半
for(int i=0;i<n;i++){
for(int j=0;j<i;j++)
swap(matrix[i][j],matrix[j][i] );
1.方法一:C++sort排序:
动态数组:
sort(ans.begin(),ans.end())
静态数组:
sort(a, a + 3)//该形式应该只能用在数组,不能用在vector