leetcode59. Spiral Matrix II
来源:互联网 发布:淘宝发布宝贝图片大小 编辑:程序博客网 时间:2024/06/05 04:31
59. Spiral Matrix II
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 ]]
解法
同leetcode54. Spiral Matrix,维护四个指针。
public class Solution { public int[][] generateMatrix(int n) { // Declaration int[][] matrix = new int[n][n]; // Edge Case if (n == 0) { return matrix; } // Normal Case int rowBegin = 0; int rowEnd = n - 1; int colBegin = 0; int colEnd = n - 1; int num = 1; //change while (rowBegin <= rowEnd && colBegin <= colEnd) { for (int i = colBegin; i <= colEnd; i++) { matrix[rowBegin][i] = num++; //change } rowBegin++; for (int i = rowBegin; i <= rowEnd; i++) { matrix[i][colEnd] = num++; //change } colEnd--; for (int i = colEnd; i >= colBegin; i--) { if (rowBegin <= rowEnd) matrix[rowEnd][i] = num++; //change } rowEnd--; for (int i = rowEnd; i >= rowBegin; i--) { if (colBegin <= colEnd) matrix[i][colBegin] = num++; //change } colBegin++; } return matrix; }}
阅读全文
1 0
- Leetcode59 Spiral Matrix II
- Leetcode59. Spiral Matrix II
- leetcode59. Spiral Matrix II
- leetcode59. Spiral Matrix II
- LeetCode59——Spiral Matrix II
- leetcode59-Spiral Matrix II(生成蛇形矩阵)
- Spiral Matrix && Spiral Matrix II
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- Spiral Matrix II
- [LeetCode] Spiral Matrix II
- Spiral Matrix II
- Spiral Matrix II
- [LeetCode]Spiral Matrix II
- Spiral Matrix II
- Spiral Matrix I(II)
- 在IBM bluemix公有云上部署容器
- 微信小程序快速开发:视频指导版
- static 使用
- Go RPC
- Java生态研究
- leetcode59. Spiral Matrix II
- android crash 二 Android端线上NativeCrash收集的两种方法(下)
- LeetCode 330. Patching Array
- [R语言]查看内置数据集
- web安全学习规划
- 单例模式解析(二)
- MVP架构开发,一篇让你从看懂到会使用
- 使用JMeter进行Web 性能测试
- css布局小结