Problem 59

Spiral Matrix II

Posted by Ruizhi Ma on July 28, 2019

问题描述

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

解决思路

这题和54基本差不多,思路一样的,需要单独处理一下中间会剩下一个的情况。

代码

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        if(n <= 0 ) return res;
        
        int left = 0, right = n - 1;
        int top = 0, bottom = n - 1;
        int num = 1;
        
        while(left < right && top < bottom){
            for(int i = left; i < right; i++) res[top][i] = num++;            
            for(int i = top; i < bottom; i++) res[i][right] = num++;            
            for(int i = right; i > left; i--) res[bottom][i] = num++;
            for(int i = bottom; i > top; i--) res[i][left] = num++;
            left++;
            top++;
            right--;
            bottom--;
        }
        
        //one blank left in the center of the matrix
        if(n % 2 == 1){
            res[n / 2][n / 2] = num++;
        }
        
        return res;
    }
}

复杂度分析

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