zoukankan      html  css  js  c++  java
  • leetcode 54 Spiral Matrix ----- java

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

    这道题就是说给定一个数组,然后求一圈一圈的读取数字,然后返回,比较简单,就是注意边界条件就好了

    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<Integer>();
            if( matrix.length == 0)
                return result;
            int left = 0,right = matrix[0].length-1;
            int num = matrix.length>matrix[0].length?matrix[0].length:matrix.length;
            num = num%2 == 0?num/2:num/2+1;
            for(int circle = 0 ;circle<num;circle++){
                if( circle == matrix.length-circle-1){//只有一行
                    for( int i = left;i<=right;i++)
                        result.add(matrix[circle][i]);
                    return result;
                }
                if( left == right){//只有一列
                    for( int i = circle;i<matrix.length-circle;i++)
                        result.add(matrix[i][right]);
                    return result;
                }
                for( int i = left;i<=right;i++)
                    result.add(matrix[circle][i]);
                for( int i = circle+1;i<matrix.length-circle;i++)
                    result.add(matrix[i][right]);
                for( int i = right-1;i>=left;i--)
                    result.add(matrix[matrix.length-circle-1][i]);
                for( int i = matrix.length-circle-2;i>circle;i--)
                    result.add(matrix[i][left]);
                left++;
                right--;
            }
            return result;
        }
    }
  • 相关阅读:
    VS2015 update3 安装 asp.net core 失败
    connection timeout 和command timeout
    安装.NET Core
    xamarin 学习笔记02- IOS Simulator for windows 安装
    xamarin 学习笔记01-环境配置
    BotFramework学习-02
    BotFramework学习-01
    正则表达式
    获取指定字节长度的字符串
    pdf生成器
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5750766.html
Copyright © 2011-2022 走看看