zoukankan      html  css  js  c++  java
  • leetcode54- Spiral Matrix- medium

    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].

    每一while循环内做一次圈打印。一圈打印做4个for循环,每个for循环做一个方向。做好后更新一下某个方向的边界。

    细节:中间需要检查一下是否会因为奇数窄形状导致的同条回荡。

    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<>();
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return result;
            }
            
            int m = matrix.length, n = matrix[0].length;
            int top = 0, bottom = m - 1, left = 0, right = n - 1;
            
            while (top <= bottom && left <= right) {
                for (int i = left; i <= right; i++) {
                    result.add(matrix[top][i]);
                }
                top++;
                
                for (int i = top; i <= bottom; i++) {
                    result.add(matrix[i][right]);
                }
                right--;
                
                // 为了避免那种窄的,单数行的最后左右回荡两次
                if (top > bottom || left > right) {
                    break;
                }
                
                for (int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }
                bottom--;
                
                for (int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
                left++;
            }
            
            return result;
        }
    }
  • 相关阅读:
    解决loss值不下降问题(转)
    c++ int转string
    图的遍历
    JavaScript类型和语法
    cesium清除选定事件
    cesium中divPoint展示数据
    cesium安装及第一个示例
    2、cesium页面小控件的隐藏
    4、cesium场景出图,打印图件
    5、cesium点击面高亮事件
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7975908.html
Copyright © 2011-2022 走看看