1.题目内容
2.题目思路
保持循环不变量;
例如和二分检索一样确定好你所采取的原则如左闭右开等,注意边界条件一致,否则容易把自己绕迷糊,这题看起来简单,但还是有一些需要注意的细节地方;
3.错误代码
class Solution {
public: // 左闭右开
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int startx = 0, starty = 0;
int size = 1;
int count = 1;
int i = 0, j = 0;
int h = n / 2;
while (h--) {
for (j = startx; j < n - size; j++) {
res[i][j] = count++;
}
for (i = starty; i < n - size; i++) {
res[i][j] = count++;
}
for (; j > startx; j--) {
res[i][j] = count++;
}
for (; i > starty; i--) {
res[i][j] = count++;
}
startx++;
starty++;
size++;
}
if (n % 2 != 0) {
res[n / 2][n / 2] = count;
}
return res;
}
};
4.分析结果
我们注意到似乎在res[1][1]的位置该出现的13出现在了res[0][1]处,在debug 后我们发现每次while循环结束我们增加了startx,starty,size的值,但这时i的值并没有改变,所以会出现上述情况。
5.解决方法
每次while循环开始i=startx,y=starty;先改变i,j的值,而不是在for里面赋初值。注意for循环不需要赋初值的写法 for (; j < n - size; j++)
6.正确代码
class Solution {
public: // 左闭右开
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int startx = 0, starty = 0;
int size = 1;
int count = 1;
int i = 0, j = 0;
int h = n / 2;
while (h--) {
i = starty;
j = starty;
for (; j < n - size; j++) {
res[i][j] = count++;
}
for (; i < n - size; i++) {
res[i][j] = count++;
}
for (; j > startx; j--) {
res[i][j] = count++;
}
for (; i > starty; i--) {
res[i][j] = count++;
}
startx++;
starty++;
size++;
}
if (n % 2 != 0) {
res[n / 2][n / 2] = count;
}
return res;
}
};
ok拿下