LeetCode:M59. Spiral Matrix II
来源:互联网 发布:淘宝客返利怎么设置 编辑:程序博客网 时间:2024/06/05 17:31
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 ]]
//TC=O(n^2)public class Solution { public int[][] generateMatrix(int n) { //special case if(n==0) return new int[0][0]; int[][] res = new int[n][n]; int num = 1; int top=0, right=n-1, bottom=n-1, left=0; while(top<bottom){ //上边框 for(int i=left; i<right; i++){ res[top][i]=num; num++; } //右边框 for(int i=top; i<bottom; i++){ res[i][right]=num; num++; } //下边框 for(int i=right; i>left; i--){ res[bottom][i]=num; num++; } //左边框 for(int i=bottom; i>top; i--){ res[i][left]=num; num++; } //这里容易遗漏 top++; right--; bottom--; left++; } //when top=bottom, it comes to the center if(num==n*n) res[top][top]=num; return res; }}
阅读全文
0 0
- LeetCode:M59. Spiral Matrix II
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode]Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode-Spiral Matrix II
- [leetcode] Spiral Matrix II
- LeetCode - Spiral Matrix II
- Leetcode: Spiral Matrix II
- 【LeetCode】Spiral Matrix II
- Leetcode Spiral Matrix II
- [LeetCode] Spiral Matrix II
- LeetCode | Spiral Matrix II
- LeetCode Spiral Matrix II
- Leetcode: Spiral Matrix II
- 基础整理-关键字
- JPA关联关系映射
- Java中的二进制及基本的位运算
- CodeForces 149D
- 最大连续子序列求和
- LeetCode:M59. Spiral Matrix II
- 个人软件开发职业技能计划书
- c++ set
- python函数
- 1016. Phone Bills (25)
- JAVA第七章-集合(三)
- 初学R语言
- Java中Comparable和Comparator区别小结
- 制作动图——imagemagick