leetcode 59. Spiral Matrix II-螺旋矩阵|清晰思路
2016-05-31 09:38
387 查看
原题链接:59. Spiral Matrix II
【思路】
遍历图解如上图所示,n 分为偶数和奇数两种情况。当 n 为偶数时,最后一次遍历刚好添加完毕;当 n 为奇数时,最后还需要进行一次添加操作⑤。另外,注意我所定义的 x 方向是竖向,y 方向是横向的。
cases passed. Runtime: 0
ms Your runtime beats 20.33% of javasubmissions.
Python 在语法上做了小小的优化,将4个循环合并:
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res, step, x, y, num = [[0]*n for i in range(n)], n-1, 0, 0, 1
dx, dy = [0,1,0,-1], [1,0,-1,0]
while step > 0 :
for i in range(4) :
for j in range(step) :
res[x][y] = num
x, y, num = x+dx[i], y+dy[i], num+1
step -= 2
x,y = (n-step)/2, (n-step)/2
if step == 0 : res[x][y] = num
return res21 / 21 test
cases passed. Runtime: 60
ms Your runtime beats 22.66% of pythonsubmissions.
【思路】
遍历图解如上图所示,n 分为偶数和奇数两种情况。当 n 为偶数时,最后一次遍历刚好添加完毕;当 n 为奇数时,最后还需要进行一次添加操作⑤。另外,注意我所定义的 x 方向是竖向,y 方向是横向的。
public class Solution { public int[][] generateMatrix(int n) { int[][] res = new int ; int num=1, d=n-1, x=(n-d)/2, y=(n-d)/2; while (d > 0) { for(int i=0; i<d; i++) res[x][y+i] = num++; //① y += d; for(int i=0; i<d; i++) res[x+i][y] = num++; //② x += d; for(int i=0; i<d; i++) res[x][y-i] = num++; //③ y = (n-d) / 2; for(int i=0; i<d; i++) res[x-i][y] = num++; //④ d -= 2; x = (n-d) / 2; y = (n-d) / 2; } if (d==0) res[x][y] = num; //⑤ return res; } }21 / 21 test
cases passed. Runtime: 0
ms Your runtime beats 20.33% of javasubmissions.
Python 在语法上做了小小的优化,将4个循环合并:
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res, step, x, y, num = [[0]*n for i in range(n)], n-1, 0, 0, 1
dx, dy = [0,1,0,-1], [1,0,-1,0]
while step > 0 :
for i in range(4) :
for j in range(step) :
res[x][y] = num
x, y, num = x+dx[i], y+dy[i], num+1
step -= 2
x,y = (n-step)/2, (n-step)/2
if step == 0 : res[x][y] = num
return res21 / 21 test
cases passed. Runtime: 60
ms Your runtime beats 22.66% of pythonsubmissions.
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 介绍一款信息管理系统的开源框架---jeecg
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- install and upgrade scrapy
- Scrapy的架构介绍