59. Spiral Matrix II
来源:互联网 发布:淘宝没有品牌无法发布 编辑:程序博客网 时间:2024/05/01 22:31
题目: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 ]]
类似于剥洋葱,一圈一圈的写入。设置4个指针,分别是left、right、top、bottom,先写最外圈 第一行->右竖列->最下行->左竖列,然后写倒数第二圈……
public class Solution { /** * 简化为剥洋葱的模式,一层一层的剥开 */ public int[][] generateMatrix(int n) { int[][]a=new int[n][n]; if(n==0) return a; int left=0,top=0,right=n-1,bottom=n-1; int cur=1; while(left<=right && top<=bottom){ for(int i=left;i<=right;i++){ a[top][i]=cur++; } for(int i=top+1;i<=bottom;i++){ a[i][right]=cur++; } for(int i=right-1;i>=left;i--){ a[bottom][i]=cur++; } for(int i=bottom-1;i>top;i--){ a[i][left]=cur++; } left++; top++; right--; bottom--; } return a; }}
0 0
- 59.Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- C primer plus 第八章 例题疑问(递归)(求解答求回复)
- App Store研究:iOS APP提交上架最新流程
- 图片的分辨率大于设备分辨率或者小于设备的分辨率的显示问题
- 常用排序算法的时间复杂度和空间复杂度
- Web提醒服务的四种实现方式比较
- 59. Spiral Matrix II
- call by value 和 call by reference
- [Android进阶]Java、Android 内存泄漏总结
- C#神器 委托 + Unity神器 协程
- THE ONE使用笔记(3)——DirectDelivery源码分析
- [HDU 4336] Card Collector (期望DP)
- (2.2.8.4 & 4.4.15.1)Gradle:multiDexEnabled之DEX 方法超过64K限制和gradle编译OOM问题解决
- 【Arduino官方教程第零辑】基础部分 2-1 数字引脚
- Python in Ubuntu Environment