• 54. Spiral Matrix java solutions


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

    For example,
    Given the following matrix:

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

    You should return [1,2,3,6,9,8,7,4,5].

    Subscribe to see which companies asked this question

     1 public class Solution {
     2     public List<Integer> spiralOrder(int[][] matrix) {
     3         List<Integer> ans = new ArrayList<Integer>();
     4         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return ans;
     5         int startx = 0,starty = 0,endx = matrix[0].length-1,endy = matrix.length-1;
     6         
     7         while(startx <= endx && starty <= endy){
     8             for(int i = startx;i<=endx && starty <= endy;i++){// 该题这里需要判断下 starty endy 的边界,不然容易重复加入list
     9                 ans.add(matrix[starty][i]);
    10             }
    11             starty++;
    12             
    13             for(int i = starty;i<=endy && startx <= endx;i++){
    14                  ans.add(matrix[i][endx]);
    15             }
    16             endx--;
    17             
    18             for(int i = endx;i>=startx && starty <= endy;i--){
    19                 ans.add(matrix[endy][i]);
    20             }
    21             endy--;
    22             
    23             for(int i = endy;i>=starty && startx <= endx;i--){
    24                 ans.add(matrix[i][startx]);
    25             }
    26             startx++;
    27         }
    28         return ans;
    29     }
    30 }

    对比59

    Spiral Matrix II java solutions

    http://www.cnblogs.com/guoguolan/p/5620000.html

  • 相关阅读:
    java之类的封装
    java飞机大战之子弹的自动生成
    java之线程飞机大战制作
    java线程游戏之背景图片的移动
    mysql的安装以及简单的命令符
    java之控制多幅图片
    java之线程
    JAVA之数组队列
    java之链表
    python之数据库的操作(课前准备)
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5620070.html
Copyright © 2020-2023  润新知