Wednesday, November 25, 2015

[leetcode[ Spiral Matrix

想想奇数最后一行的方向 就搞掂
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
    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 hStart = 0;
        int hEnd = matrix[0].length-1;
        int vStart = 0;
        int vEnd = matrix.length-1;

        while (hStart < hEnd && vStart < vEnd){
            for (int i = hStart; i < hEnd; i++) result.add(matrix[vStart][i]);
            for (int i = vStart; i < vEnd; i++) result.add(matrix[i][hEnd]);
            for (int i = hEnd; i > hStart; i--) result.add(matrix[vEnd][i]);
            for (int i = vEnd; i > vStart; i--) result.add(matrix[i][hStart]);
            hStart++;
            hEnd--;
            vStart++;
            vEnd--;
        }

        if (hStart == hEnd && vStart <= vEnd){
            for (int i = vStart; i <= vEnd; i++) result.add(matrix[i][hStart]);
        }else if (vStart == vEnd && hStart <= hEnd){
            for (int i = hStart; i <= hEnd; i++) result.add(matrix[vStart][i]);
        }

        return result;
    }
}

No comments:

Post a Comment