TypechoJoeTheme

IT技术分享

统计

[LeetCode 54] Spiral Matrix [Java] [Runtime: 2MS]

2017-08-14
/
0 评论
/
606 阅读
/
正在检测是否收录...
08/14

1. Description

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

2. Runtime Distribution

3. Submission Details

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

5. Code

import java.util.ArrayList;
import java.util.List;

public class LeetCode0054 {
    public List<Integer> spiralOrder(int[][] matrix)
    {
        List<Integer> result = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }

        int firstRow = 0, lastRow = matrix.length;
        int firstCol = 0, lastCol = matrix[0].length;

        while (firstRow < lastRow && firstCol < lastCol) {
            int i = firstRow, j = firstCol;
            if (j == lastCol) {
                break;
            }
            for (; j < lastCol; j++) {
                result.add(matrix[i][j]);
            }
            lastCol--;
            j--;
            i++;
            if (i == lastRow) {
                break;
            }
            for (; i < lastRow; i++) {
                result.add(matrix[i][j]);
            }
            lastRow--;
            i--;
            j--;
            if (j < firstCol) {
                break;
            }
            for (; j >= firstCol; j--) {
                result.add(matrix[i][j]);
            }
            firstCol++;
            j++;
            i--;
            if (i <= firstRow) {
                break;
            }
            for (; i > firstRow; i--) {
                result.add(matrix[i][j]);
            }
            firstRow++;
        }

        return result;
    }

    public static void main(String[] args)
    {
        LeetCode0054 leetcode = new LeetCode0054();

        int[][] matrix = { { 7 }, { 9 }, { 6 } };
        List<Integer> result = leetcode.spiralOrder(matrix);
        for (int i = 0; i < result.size(); i++) {
            System.out.print(result.get(i) + " ");
        }
    }
}
Matrix
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/712/(转载时请注明本文出处及文章链接)