> 文档中心 > [New Star] LeetCode螺旋矩阵

[New Star] LeetCode螺旋矩阵


行百里者半九十 富婆dd我,我缺爱

[New Star] LeetCode螺旋矩阵

小白我继续跟进算法学习,这是代码随想录数组的最后一小节,玩的是数学思想,基本没有用到编程思想,只用基本的语法就可以做到,但没有接触过这类题型也很难入手。(其实就是我自己菜的一批!!55555)但是遇到一种解法非常妙!妙不可言,我直呼内涵!

第一题是 59. 螺旋矩阵 II

给你一个正整数 n ,生成一个包含 1到 n2所有元素,且元素按顺时针顺序螺旋排列的 n x n正方形矩阵 matrix。

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

[New Star] LeetCode螺旋矩阵

因为是顺时针螺旋,做法是定好边界,从上右下左不断缩小边界

class Solution {    public int[][] generateMatrix(int n) { //定边界 int left = 0, top = 0,right = n -1, bottom  = n -1,count = 1; int [][] num  = new int [n][n]; while(count  <=n*n){//计数     for(int  i = left;i <= right;i++) num[top][i] = count++;//将top数存入数组,缩小上边界     top++;     for(int i = top; i <= bottom ; i++)  num[i][right] = count++;     right--;//这里是--     for( int  i  = right ; i >= left; i --)num[bottom][i] = count++;//i是--,right 比left大     bottom--;     for( int i = bottom ;i>= top ;i--) num[i][left] = count ++;     left++;   } return num;    }}

第二题 :54. 螺旋矩阵

给你一个 m行 n列的矩阵 matrix,请按照 顺时针螺旋顺序,返回矩阵中的所有元素。

这道题与上道题的区别是:上道题是正方形,而这是一个长方形,所以right与bottom是不一定相等的;

class Solution {//然后才发现是list    public List<Integer> spiralOrder(int[][] matrix) {//返回的是链表 int m =matrix.length,n = matrix[0].length ; int  left  = 0, right =n - 1 , top = 0, bottom  = m -1,count = 1; List<Integer> num = new LinkedList<>();//创建链表 while( count <=m*n){     for(int i = left; i <= right; i++) {  if(count <=m*n){num.add( matrix[top][i]);count++ ;  }     }     top++;     for(int i  = top; i <= bottom; i++) {  if(count <=m*n){      num.add(  matrix[i][right]);count++;  }     }     right--;     for( int i  = right;i >=left; i--){  if(count <=m*n) {      num.add(  matrix[bottom][i]);      count++;  }     }     bottom--;     for(int i=  bottom;i >= top; i--) {  if(count <=m*n){      num.add(  matrix[i][left]);count++;  }     }     left++; } return num;    }}

第三题是剑指 Offer 29. 顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

与第二题类似,但我踩到java.lang.ArrayIndexOutOfBoundsException的坑,我遇到这个错误,一直没注意到开始length -1的问题,因为当二维数组为空时,它便没有所谓的nums[0]这个元素,,0作为下标表示这个元素存在,而空表示不存在,也即数组越界了;解决方案就是先判断二维数组是不是空
还有一点事,因为是长方形,在每次缩进完边界后需要判断是否结束,否则会重复输入

class Solution {    public int[] spiralOrder(int[][] matrix) {  //防止空数组 if(matrix.length == 0) return new int[0]; int left = 0 , m = matrix.length, n = matrix[0].length ; int right = n -1,top = 0, bottom = m-1 ; int count = 0; int [] num = new int[m*n]; while(count <m*n){     for(int i = left ; i <= right; i++)  num[count++] = matrix[top][i];     if(++top > bottom) break;     for( int i = top ; i <= bottom; i++ )  num[count++]  = matrix[i][right];     if(--right <left  ) break;     for(int i = right ;i >= left; i-- ) num[count++] = matrix[bottom][i];     if(--bottom  <top)  break;     for(int i = bottom ; i>= top; i--)  num[count++]  =matrix [i][left];     if(++left> right)  break; } return num;    }}

最后祝大家吉时吉日喜如风,丰年丰月如风筝,争富争财争长寿,寿山寿海寿长生,生富生才生贵子,子孝孙贤代代荣,荣华富贵年年有,有钱有势有前程!
[New Star] LeetCode螺旋矩阵