NO19、顺时针打印矩阵 (好题,值得再做一遍)

19、顺时针打印矩阵 好题,值得再做一遍

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
示例1
输入

[[1,2],[3,4]]

返回值

[1,2,4,3]
1、有点难,在力扣上写了好久

主要就是分析清楚上下左右的情况

执行用时:20 ms, 在所有 C++ 提交中击败了87.56%的用户

内存消耗:10 MB, 在所有 C++ 提交中击败了100.00%的用户

执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户

内存消耗:6.7 MB, 在所有 C++ 提交中击败了100.00%的用户

vector<int> spiralOrder(vector<vector<int>>& matrix) {
    if (matrix.size()==0) return vector<int>();
    if (matrix.size() == 1) return matrix[0];
    int row = matrix.size(), col = matrix[0].size();
    int left = 0, right = 0, top = 0, bottom = 0;
    vector<int> result;
    while (left + right < col && top + bottom < row) {

        for (int i = left; i < col - left - right + left; ++i) {
            //cout << matrix[top][i];
            result.push_back(matrix[top][i]);
        }

        top++;
        //cout << " top " <<top<<bottom<< endl;
        if (top + bottom == row) break;


        for (int i = top; i < row - top - bottom + top; ++i) {
            //cout << matrix[i][col - right - 1];
            result.push_back(matrix[i][col - right - 1]);
        }        
        right++;
        //cout << "right"<<left<<right<<endl;
        if (left + right == col) break;


        for (int i = col-right-1; i >= left ; --i) {
            //cout << matrix[row - bottom - 1][i];
            result.push_back(matrix[row - bottom - 1][i]);
        }
        bottom++;
        //cout << " bottom " << top << bottom << endl;
        if (top + bottom == row) break;


        for (int i = row-bottom-1; i >= top; --i) {
            //cout << matrix[i][left];
            result.push_back(matrix[i][left]);
        }
        left++;
        //cout << "left" << left << right << endl;
    }
    return result;
}
2、新的写法,这种其实更好理解

执行用时:24 ms, 在所有 C++ 提交中击败了56.85%的用户

内存消耗:10 MB, 在所有 C++ 提交中击败了100.00%的用户

vector<

剩余60%内容,订阅专栏后可继续查看/也可单篇购买

带你刷完67道剑指offer 文章被收录于专栏

- 本专栏汇集了67道剑指offer的一些精妙解法,不少题有5-6种解法之多,有些题目二刷三刷的解法也不一样。 - 本专栏帮助我拿到6个互联网大厂offer,最终圆梦字节跳动公司。

全部评论
思路清晰,秀哥加油奥
点赞 回复 分享
发布于 2020-12-25 16:41

相关推荐

点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务