zoukankan      html  css  js  c++  java
  • 54. 螺旋矩阵

    采用模拟的方案顺时针遍历所有元素

    时间O(m*n)(需要遍历所有节点),空间O(1)

     1     public List<Integer> spiralOrder(int[][] matrix) {
     2         LinkedList<Integer> res = new LinkedList<>();
     3         if(matrix==null || matrix.length==0) return res;
     4         int left=0,right=matrix[0].length-1,top=0,bottom=matrix.length-1;
     5         int numEle = matrix.length*matrix[0].length;
     6         while(numEle>0){
     7             // 由左向右遍历
     8             for(int i=left; i<=right && numEle>0 ;i++){
     9                 res.add(matrix[top][i]);
    10                 numEle--;
    11             }
    12             top++;
    13             // 由上向下遍历
    14             for(int i=top; i<=bottom && numEle>0 ; i++){
    15                 res.add(matrix[i][right]);
    16                 numEle--;
    17             }
    18             right--;
    19             // 由右向左遍历
    20             for(int i=right;i>=left && numEle>0;i--){
    21                 res.add(matrix[bottom][i]);
    22                 numEle--;
    23             }
    24             bottom--;
    25             // 由下向上遍历
    26             for(int i=bottom;i>=top && numEle>0;i--){
    27                 res.add(matrix[i][left]);
    28                 numEle--;
    29             }
    30             left++;
    31         }
    32         return res;
    33     }
    争取早日不再是一只菜鸡
  • 相关阅读:
    Sqli-Labs less46-53
    Sqli-Labs less38-45
    Sqli-Labs less32-37
    移动web问题小结
    伪类与伪元素
    HTML5 视频直播
    判断鼠标移入移出元素时的方向
    Input操作文件
    利用WebStorm来管理你的Github
    webkit开发,app移动前端知识点
  • 原文地址:https://www.cnblogs.com/jchen104/p/14816614.html
Copyright © 2011-2022 走看看