码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Spiral Matrix II

时间:2014-10-13 09:58:09      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   sp   div   

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一样的处理,甚至还简单一些,这个确定是方阵。分层,然后按照上右下左的顺序放入数组中。每个元素只访问一次,时间复杂度是O(n^2)。

 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int[][] res = new int[n][n];
 4         if (n < 0) return null;
 5         int levelNum = n / 2;
 6         int count = 1;
 7         for (int level=0; level<levelNum; level++) {
 8             for (int i=level; i<n-1-level; i++) {
 9                 res[level][i] = count++;
10             }
11             for (int i=level; i<n-1-level; i++) {
12                 res[i][n-1-level] = count++;
13             }
14             for (int i=n-1-level; i>level; i--) {
15                 res[n-1-level][i] = count++;
16             }
17             for (int i=n-1-level; i>level; i--) {
18                 res[i][level] = count++;
19             }
20         }
21         if (n % 2 == 1) {
22             res[levelNum][levelNum] = count;
23         }
24         return res;
25     }
26 }

 

Leetcode: Spiral Matrix II

标签:style   blog   http   color   io   ar   for   sp   div   

原文地址:http://www.cnblogs.com/EdwardLiu/p/4021422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!