标签:http 标签 目标 runtime ret algorithm cheng pre log
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Java Solution:
Runtime beats 57.87%
完成日期:07/20/2017
关键词:Array
关键点:螺旋矩阵的遍历模式;设置四个边界值
1 public class Solution 2 { 3 public int[][] generateMatrix(int n) 4 { 5 int[][] res = new int[n][n]; 6 7 int total = n*n; 8 int num = 1; 9 10 int rowBegin = 0; 11 int rowEnd = n-1; 12 int colBegin = 0; 13 int colEnd = n-1; 14 15 while(num <= total) 16 { 17 // traverse right (y changes) 18 for(int y=colBegin; y<=colEnd; y++) 19 res[rowBegin][y] = num++; 20 21 rowBegin++; // move down one row 22 23 // traverse down (x changes) 24 for(int x=rowBegin; x<=rowEnd; x++) 25 res[x][colEnd] = num++; 26 27 colEnd--; // move left one column 28 29 // traverse left (y changes) 30 for(int y=colEnd; y>=colBegin; y--) 31 res[rowEnd][y] = num++; 32 33 rowEnd--; // move up one row 34 35 // traverse up (x changes) 36 for(int x=rowEnd; x>=rowBegin; x--) 37 res[x][colBegin] = num++; 38 39 colBegin++; // move right one column 40 41 } 42 43 return res; 44 } 45 }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
LeetCode 59. Spiral Matrix II (螺旋矩阵之二)
标签:http 标签 目标 runtime ret algorithm cheng pre log
原文地址:http://www.cnblogs.com/jimmycheng/p/7215630.html