Problem 54

Spiral Matrix

Posted by Ruizhi Ma on July 27, 2019

问题描述

https://leetcode.com/problems/spiral-matrix/

解决思路

设置四个角,然后不断地以螺旋状将数组加入res结果集。最后需要单独处理一下最后剩下一行或者一列的情况。

代码

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        LinkedList<Integer> res = new LinkedList<>();
        
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
    
        int left = 0, right = matrix[0].length - 1;
        int top = 0, bottom = matrix.length - 1;
        
        while(left < right && top < bottom){
            //in every row, from left to right
            for(int i = left; i < right; i++) res.add(matrix[top][i]);
            //in every coloum, from top to bottom
            for(int i  = top; i < bottom; i++) res.add(matrix[i][right]);
            //in every row, from right to left
            for(int i = right; i > left; i--) res.add(matrix[bottom][i]);
            //every coloum, from bottom to top
            for(int i = bottom; i > top; i--) res.add(matrix[i][left]);
            left++;
            right--;
            top++;
            bottom--;
        }
        
        //only left one coloum
        if(left == right){
            for(int i = top; i <= bottom; i++) res.add(matrix[i][left]);
        }else if(top == bottom){//only left one row
            for(int i = left; i <= right; i++) res.add(matrix[top][i]);
        }
                                                      
        return res;
    
    
    
    
    
    }
}

复杂度分析

  1. 时间复杂度:O(n)
  2. 空间复杂度:O(n)