• 剑指Offer——顺时针打印矩阵


    题目描述:

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,

    例如,如果输入如下矩阵:

    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 class Solution {
     2 public:
     3     vector<int> printMatrix(vector<vector<int> > matrix) {
     4         int h = matrix.size();
     5         int w = matrix[0].size();
     6         vector<int> res;
     7         if(h == 0 || w == 0) return res;
     8         int left = 0, right = w - 1, top = 0, bottom = h - 1;
     9         while(left <= right && top <= bottom) {
    10             int i = top, j = left;
    11             for(j = left; j < right; j++) res.push_back(matrix[i][j]);  // 向右打印
    12             if(top == bottom) { // 最后一行一次性打印到末尾
    13                 res.push_back(matrix[i][j]);
    14                 break;
    15             }
    16             for(i = top; i < bottom; i++) res.push_back(matrix[i][j]);  // 向下打印
    17             if(left == right) { // 最后一列一次性打印到末尾
    18                 res.push_back(matrix[i][j]);
    19                 break;
    20             }
    21             for(j = right; j > left; j--) res.push_back(matrix[i][j]);  // 向左打印
    22             for(i = bottom; i > top; i--) res.push_back(matrix[i][j]);  // 向上打印
    23             left++; right--;
    24             top++; bottom--;
    25         }
    26         return res;
    27     }
    28 };
  • 相关阅读:
    mongodb的热备工具pbm-agent
    注释
    mongodb的启动配置查询serverCmdLineOpts
    副本集状态
    分片集群的serverStatus监控
    副本集的replSetGetStatus监控
    京东
    副本集的replSetGetConfig监控
    mysql的replace函数
    副本集的serverStatus监控
  • 原文地址:https://www.cnblogs.com/jacen789/p/7747068.html
Copyright © 2020-2023  润新知