leetcode算法练习【54】螺旋矩阵

所有题目源代码:Git地址

题目

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

方案

class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            int row = matrix.length;
            if(row<1) return new ArrayList<>();
            int cul = matrix[0].length;
            int rowstart = 0;
            int culstart = 0;
            int rowend = row-1;
            int culend = cul-1;
            List<Integer> res = new ArrayList<>();
            while(culstart<culend&&rowstart<rowend){
                //→
                for(int i=culstart;i<=culend;i++){
                    res.add(matrix[rowstart][i]);
                }
                rowstart++;
                //↓
                for(int j = rowstart;j<=rowend;j++){
                    res.add(matrix[j][culend]);
                }
                culend--;
                //←
                for(int i = culend;i>=culstart;i--){
                    res.add(matrix[rowend][i]);
                }
                rowend--;
                //↑
                for(int j = rowend;j>=rowstart;j--){
                    res.add(matrix[j][culstart]);
                }
                culstart++;
            }
            if (row*cul>res.size())
            if (rowstart<rowend){
                for(int j = rowstart;j<=rowend;j++){
                    res.add(matrix[j][culend]);
                }
            }else if (culstart<culend){
                for(int i=culstart;i<=culend;i++){
                    res.add(matrix[rowstart][i]);
                }
            }else if (rowstart==rowend&&culstart==culend){
                res.add(matrix[rowstart][culstart]);
            }
            return res;
        }
    }
复杂度计算
  • 时间复杂度:O(mn)
  • 空间复杂度:O(1)
原创文章 179 获赞 270 访问量 34万+

猜你喜欢

转载自blog.csdn.net/symuamua/article/details/106165667
今日推荐