zoukankan      html  css  js  c++  java
  • [LeetCode]Spiral Matrix

    题目描述:

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

    For example,
    Given the following matrix:

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

    You should return [1,2,3,6,9,8,7,4,5].

    解题思路:

     1 class Solution {
     2 public:
     3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
     4         vector<int> result;
     5         if (matrix.size() == 0) {
     6             return result;
     7         }
     8         int left = 0;
     9         int right = matrix[0].size() - 1;
    10         int up = 0;
    11         int down = matrix.size() - 1;
    12         
    13         int n = matrix.size() * matrix[0].size();
    14         
    15         while (true) {
    16             for (int i = left; i <= right; ++i) {
    17                 result.push_back(matrix[up][i]);
    18                 --n;
    19             }
    20             if (n <= 0) {
    21                 break;
    22             }
    23             
    24             up += 1;
    25             for (int i = up; i <= down; ++i) {
    26                 result.push_back(matrix[i][right]);
    27                 --n;
    28             }
    29             if (n <= 0) {
    30                 break;
    31             }
    32             
    33             right -= 1;
    34             for (int i = right; i >= left; --i) {
    35                 result.push_back(matrix[down][i]);
    36                 --n;
    37             }
    38             if (n <= 0) {
    39                 break;
    40             }
    41         
    42             down -= 1;
    43             for (int i = down; i >= up; --i) {
    44                 result.push_back(matrix[i][left]);
    45                 --n;
    46             }
    47             left += 1;
    48             
    49             if (n <= 0) {
    50                 break;
    51             }
    52         }
    53         
    54         return result;
    55     }
    56 };
  • 相关阅读:
    java中CyclicBarrier的使用
    java并发中CountDownLatch的使用
    java中Locks的使用
    java 中的fork join框架
    java中ThreadPool的介绍和使用
    java中的daemon thread
    java中interrupt,interrupted和isInterrupted的区别
    java中的Atomic类
    怎么在java中关闭一个thread
    java中join的使用
  • 原文地址:https://www.cnblogs.com/skycore/p/5269438.html
Copyright © 2011-2022 走看看