zoukankan      html  css  js  c++  java
  • leetcode 54. Spiral Matrix

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    Example 1:

    Input:
    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]
    

    Example 2:

    Input:
    [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9,10,11,12]
    ]
    Output: [1,2,3,4,8,12,11,10,9,5,6,7]
     1 class Solution {
     2 public:
     3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
     4         vector<int> res;
     5         int m = matrix.size();
     6         if (m == 0)
     7             return res;
     8         int n = matrix[0].size();
     9         int cnt = 0;
    10         res.resize(m * n);
    11         int start_row = 0, start_col = 0, end_row = m - 1, end_col = n - 1;
    12         while (cnt < m * n) {
    13             for (int j = start_col; cnt < m * n && j <= end_col; j++) {
    14                 res[cnt++] = matrix[start_row][j];
    15             }
    16             for (int i = start_row + 1; cnt < m * n && i <= end_row; i++) {
    17                 res[cnt++] = matrix[i][end_col];
    18             }
    19             for (int j = end_col - 1; cnt < m * n && j >= start_col; j--) {
    20                 res[cnt++] = matrix[end_row][j];
    21             }
    22             for (int i = end_row - 1; cnt < m * n && i > start_row; i--) {
    23                 res[cnt++] = matrix[i][start_col];
    24             }
    25             start_row++;
    26             start_col++;
    27             end_row--;
    28             end_col--;
    29         }
    30         return res;
    31     }
    32 };
  • 相关阅读:
    全文检索原理
    UBER的故事
    grails 优缺点分析
    微博轻量级RPC框架Motan
    基于redis 实现分布式锁的方案
    eggjs中cache-control相关问题
    mysql导入导出数据
    jenkins项目用户权限相关
    jenkins+gogs,服务随代码更新
    js/nodejs导入Excel相关
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11530709.html
Copyright © 2011-2022 走看看