Leetcode#59 Spiral Matrix II
相比于Spiral Matrix(参见这篇文章)要简单一些,因为是方阵,所以代码简洁一些。
注意当n是奇数的时候,中心小块要单独赋值(代码21行)
代码:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > matrix(n, vector<int>(n, ));
int len = n - ;
int i = ;
int j = ;
int count = ;
while (len > ) {
for (int k = ; k < len; k++)
matrix[i][j++] = count++;
for (int k = ; k < len; k++)
matrix[i++][j] = count++;
for (int k = ; k < len; k++)
matrix[i][j--] = count++;
for (int k = ; k < len; k++)
matrix[i--][j] = count++;
i++;
j++;
len -= ;
}
if (len == )
matrix[i][j] = count;
return matrix;
}
Leetcode#59 Spiral Matrix II的更多相关文章
- [LeetCode] 59. Spiral Matrix II 螺旋矩阵 II
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. For ...
- LeetCode: 59. Spiral Matrix II(Medium)
1. 原题链接 https://leetcode.com/problems/spiral-matrix-ii/description/ 2. 题目要求 给定一个正整数n,求出从1到n平方的螺旋矩阵.例 ...
- LeetCode 59. Spiral Matrix II (螺旋矩阵之二)
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...
- [leetcode]59. Spiral Matrix II螺旋遍历矩阵2
Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral or ...
- Leetcode 54. Spiral Matrix & 59. Spiral Matrix II
54. Spiral Matrix [Medium] Description Given a matrix of m x n elements (m rows, n columns), return ...
- leetcode 54. Spiral Matrix 、59. Spiral Matrix II
54题是把二维数组安卓螺旋的顺序进行打印,59题是把1到n平方的数字按照螺旋的顺序进行放置 54. Spiral Matrix start表示的是每次一圈的开始,每次开始其实就是从(0,0).(1,1 ...
- 【leetcode】59.Spiral Matrix II
Leetcode59 Spiral Matrix II Given an integer n, generate a square matrix filled with elements from 1 ...
- 【leetcode】Spiral Matrix II
Spiral Matrix II Given an integer n, generate a square matrix filled with elements from 1 to n2 in s ...
- Java for LeetCode 059 Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...
随机推荐
- C++ string 转 char*
string 转到 char* char name[20]; string sname=GatherName[n]; strcpy(name,sname.c_str());
- 使用supervisor的一些注意事项
一直都有在使用supervisor来管理linux上的服务进程.最近有同事说有某服务貌似有问题,让上去检查一下.上去以后发现某服务反应的确很慢,所以就用supervisor重启一下.但是重启的时候就发 ...
- 《大话设计模式》ruby版代码:简单工厂模式
之前有看过<ruby设计模式>,不过渐渐的都忘记了.现在买了一个大话设计模式,看起来不是那么枯燥,顺便将代码用ruby实现了一下. # -*- encoding: utf-8 -*- #运 ...
- 值类型和引用类型(C#基础知识复习)
一.值类型和引用类型 二.值类型的赋值和相等 三.引用类型的赋值和同一
- EMVTag系列3《持卡人基本信息数据》
Ø 9F61 持卡人证件号 L:2–26 R(需求):数据应存在,在读应用数据过程中,终端不检查: (PBOC2.0第五部分中规定)芯片中持卡人姓名 5F20与持卡人姓名扩展9F0B只能使用一 ...
- printf输出格式总结
printf函数称为格式输出函数,其关键字最末一个字母f即为"格式"(format)之意.其功能是按用户指定的格式,把指定的数据显示到显示器屏幕上. printf函数调用的一般形式 ...
- 菜鸟学习Hibernate——持久层框架
一.Java操作数据库的阶段. Java对数据库进行操作经历了三个阶段. 1.1操作JDBC阶段 这个阶段就是利用JDBC类来操作数据库.这个阶段出现了两个问题: 代码过度重复:在每一次数据库操作的是 ...
- SQLserver中idendity的妙用
假设:现在有产品信息需要入库,要给每个产品按找预定的规则进行编号,编号规则如下: 产品编码:6位产品类型码+1位仓库码+2位年份+5位顺序码(要求从00001开始自增) 6位产品类型码:P00001 ...
- JVM学习总结五(番外)——VisualVM
距离上次介绍Jconsole已经时隔两周了,这期间由于工作中要用go来做一个新项目,所以精力都用在入门go上了,不过发现go语言用起来真的挺不错的,比python感觉还好点,大家没事可以了解下. ...
- iOS学习之Object-C语言内存管理高级
一.属性的内存管理