LeetCode[54] Spiral Matrix

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

复杂度
O(MN), O(1)

思路
注意循环条件。

代码

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new LinkedList<>();
        int count = 0;
        int rowlen = matrix.length;
        if(rowlen == 0) return res;
        int collen = matrix[0].length;
        //注意循环条件,要用*而不是除以,因为精度准换问题;
        while(count * 2 < rowlen && count * 2 < collen) {
            for(int i = count; i < collen - count; i ++) {
                res.add(matrix[count][i]);
            }
            for(int i = count + 1; i < rowlen - count; i ++) {
                res.add(matrix[i][collen - 1 - count]);
            }
            //只有一行或者一列的时候,就不要再继续搜索了;
            if(rowlen - count * 2 == 1 || collen - count * 2 == 1) break;
            for(int i = collen - 2 - count; i >= count; i --) {
                res.add(matrix[rowlen - 1- count][i]);
            }
            for(int i = rowlen - count - 2; i >= count + 1; i --) {
                res.add(matrix[i][count]);
            }
            count ++;
        }
        return res;
    }```

hellolittleJ17
10 声望11 粉丝