zoukankan      html  css  js  c++  java
  • LeetCode第[54]题(Java):Spiral Matrix

    题目:螺旋矩阵

    难度:Medium

    题目内容

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    翻译

    给定一个m x n元素的矩阵(m行,n列),以顺时针螺旋顺序返回矩阵的所有元素。

    Example 1:

    Input:
    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]
    

    Example 2:

    Input:
    [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9,10,11,12]
    ]
    Output: [1,2,3,4,8,12,11,10,9,5,6,7]

    我的思路:因为每一圈都是由四条边组成的,所以写一个while死循环,里面有四个for循环,每个for循环结束之后都将相应的指标减少,同时判断是否超标,超标就退出。

    eg:

    while (true) {

    // 横着 for  add 

    // top ++

    // top 是否小于bottom 是则break

    。。。

    } 

    我的代码

     1     public List<Integer> spiralOrder(int[][] matrix) {
     2         List<Integer> res = new ArrayList<Integer>();
     3         if(matrix.length == 0 || matrix[0].length == 0) return res;
     4         
     5         int top = 0;
     6         int bottom = matrix.length-1;
     7         int left = 0;
     8         int right = matrix[0].length-1;
     9         
    10         while(true){
    11             for(int i = left; i <= right; i++) res.add(matrix[top][i]);
    12             top++;
    13             if(left > right || top > bottom) break;
    14             
    15             for(int i = top; i <= bottom; i++) res.add(matrix[i][right]);
    16             right--;
    17             if(left > right || top > bottom) break;
    18             
    19             for(int i = right; i >= left; i--) res.add(matrix[bottom][i]);
    20             bottom--;
    21             if(left > right || top > bottom) break;
    22             
    23             for(int i = bottom; i >= top; i--) res.add(matrix[i][left]);
    24             left++;
    25             if(left > right || top > bottom) break;
    26         }
    27         
    28         return res;
    29     }

    我的复杂度:O(N * M)     行乘以列

    编码过程中的问题

    1、没有注意到当输入为空的数组的时候 right 和bottom都会取成负数,所以得加上判空。

    答案代码

    和我一样的。

  • 相关阅读:
    Redux React-redux 理解
    React ---- 浅谈ReactJs
    javascript --- 鼠标事件
    javaScript --- localStorage 本地存储
    javascript -- 对象(深拷贝、浅拷贝)
    javascript --- 数组输出数组中最大值最小值差值
    Css中未知 div 宽高度,水平垂直居中方法
    Windows下使用NCL(Cygwin模拟Linux环境)
    Qt加载网页(加载浏览器插件)和制作托盘后台运行(南信大财务报账看号)
    OpenGL超级宝典第5版&&GLSL法线变换
  • 原文地址:https://www.cnblogs.com/Xieyang-blog/p/9032743.html
Copyright © 2011-2022 走看看