054 Spiral Matrix

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

Example:

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

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]

解釋下題目:

就是從左上角開始螺旋打印這個數(shù)組

1. 按照要求螺旋打印唄,還能怎么樣

實際耗時:2ms

public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int row = matrix.length;
        if (0 == row) {
            //空數(shù)組就返回空
            return list;
        }
        int column = matrix[0].length;
        int count = row * column;

        //初始化四個頂點
        int row1 = 0;
        int column1 = 0;

        int row2 = 0;
        int column2 = column;

        int row3 = row;
        int column3 = column;

        int row4 = row;
        int column4 = 0;
        while (count > 0) {
            //第一趟從左往右
            for (int j = column1; j < column2; j++) {
                //System.out.print("1:");
                //System.out.println(matrix[row1][j]);
                list.add(matrix[row1][j]);
                count--;
            }
            if (0 == count) break;

            //第二趟從上往下
            for (int i = row2 + 1; i < row3; i++) {
                //System.out.print("2:");
                //System.out.println(matrix[i][column2 - 1]);
                list.add(matrix[i][column2 - 1]);
                count--;
            }
            if (0 == count) break;

            //第三趟從右到左
            for (int j = column3 - 2; j >= column4; j--) {
                //System.out.print("3:");
                //System.out.println(matrix[row3 - 1][j]);
                list.add(matrix[row3 - 1][j]);
                count--;

            }
            if (0 == count) break;

            //第四趟從下到上
            for (int i = row4 - 2; i > row1; i--) {
                //System.out.print("4:");
                //System.out.println(matrix[i][column4]);
                list.add(matrix[i][column4]);
                count--;

            }
            if (0 == count) break;

            //移動四個頂點
            row1++;
            column1++;

            row2++;
            column2--;

            row3--;
            column3--;

            row4--;
            column4++;
        }
        return list;
    }
踩過的坑:[] 空的我又忘記處理了

??思路:就是按照它說的照著打印就行了。處理的時候我是用了八個數(shù)用來記錄四個頂點的位置,其實可以只用4個數(shù),分別用來記錄行的起始位置和列的起始位置即可。還有我是當(dāng)判斷所有數(shù)字都打印過了就退出,其實也可以判斷列的起始位置重合且行的起始位置重合,說明輸出完畢,都無傷大雅。

時間復(fù)雜度O(nm) 不可能有更優(yōu)的時間解了
空間復(fù)雜度O(1)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容