leetcode
来源:互联网 发布:看电影用什么软件最好 编辑:程序博客网 时间:2024/06/06 09:26
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 ]]
Solution:
public int[][] generateMatrix(int n) { int[][] result = new int[n][n]; if (n == 0) { return result; } int rowBegin = 0; int rowEnd = n - 1; int colBegin = 0; int colEnd = n - 1; int i = 1; while (rowBegin <= rowEnd && colBegin <= colEnd) { for (int j = colBegin; j <= colEnd; j++) { result[rowBegin][j] = i++; } rowBegin++; for (int j = rowBegin; j <= rowEnd; j++) { result[j][colEnd] = i++; } colEnd--; if (rowBegin <= rowEnd) { for (int j = colEnd; j >= colBegin; j--) { result[rowEnd][j] = i++; } } rowEnd--; if (colBegin <= colEnd) { for (int j = rowEnd; j >= rowBegin; j--) { result[j][colBegin] = i++; } } colBegin++; } return result; }
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- shell 中三种引号的用法及区别
- Redis 学习笔记(六)之 set无序集合
- 机器人操作系统ROS Indigo 入门学习(7)——理解ROS Topic
- 【图像处理】IPTC Tags
- SQL中显示查询结果的前几条记录
- leetcode
- GO类型查询
- PHP调用系统函数时报错未定义解决方法
- 上传图片,头像
- struts中的全局结果页面配置
- mysql性能优化(九) mysql慢查询分析、优化索引和配置
- leetcode
- 目标检测--Training Region-based Object Detectors with Online Hard Example Mining
- xutils3解析数据: