Leetcode59螺旋矩阵II

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拿下

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值