LeetCode进阶之路(Spiral Matrix II)

来源:互联网 发布:淘宝中推广方法有哪些 编辑:程序博客网 时间:2024/06/06 02:03

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 ]]

题目:给一个n,将1至n^2间的的数按规律放到二维数组中。

思路:这题是前面做过的Spiral Matrix的升级版,也只是需要把握好边界就行。

public int[][] generateMatrix(int n) {        int[][] result = new int[n][n];int i = 1;int rowMax = n-1;int rowMin = 0;int colMax = n-1;int colMin = 0;while(i <= n*n) {for(int j = colMin; j <=colMax;j++) {result[rowMin][j] = i;i++;}rowMin++;for(int j = rowMin;j <= rowMax;j++) {result[j][colMax] = i;i++;}colMax--;for(int j = colMax;j >= colMin;j--) {result[rowMax][j] = i;i++;}rowMax--;for(int j = rowMax;j >= rowMin;j--) {result[j][colMin] = i;i++;}colMin++;}return result;    }

种一棵树最好的时间是十年前,其次是现在!

PS:最近两个星期出差,接手防火墙的项目,完全重新开始学,希望这两个星期能够尽可能多的掌握,免得回杭州后还得远程求助。老实说,网络通信这块不是自己感兴趣的,但是也不会其他方面的,只能这样继续磨着。leetcode这个一定要坚持刷下去,其他知识也要赶快自学起来了,做好跳槽的准备,网易才是我的梦想。


0 0
原创粉丝点击