2015年6月30日星期二

Spiral Matrix II leetcode

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
和Spiral Matrix类似, 但是这里是n*n的矩阵, 最后要判断n是否是奇数 如果是奇数那么还要添加中间的matrix[n/2][n/2]位置的数字 时间复杂度O(n^2)
public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        if (n == 0) {
            return res;
        }
        int num = 1;
        int mid = n / 2;
        for (int i = 0; i < mid; i++) {
            for (int j = i; j < n - i - 1; j++) {
                res[i][j] = num++;
            }
            for (int j = i; j < n - i - 1; j++) {
                res[j][n - i - 1] = num++;
            }
            for (int j = n - i - 1; j > i; j--) {
                res[n - i - 1][j] = num++;
            }
            for (int j = n - i - 1; j > i; j--) {
                res[j][i] = num++;
            }
        }
        if ((n % 2) == 1) {
            res[mid][mid] = num++;
        }
        return res;
    }
}

没有评论:

发表评论