题目
https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
解法
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 30 31 32 33 34 35 36 37 38 39
| public int[] spiralOrder(int[][] matrix) { if (matrix == null || matrix.length == 0) { return new int[0]; } int rowLen = matrix.length; int colLen = matrix[0].length; List<Integer> res = new ArrayList<>(); int top = 0, right = colLen-1, bottom = rowLen-1, left =0; while (top<bottom && left < right) { for(int i=left; i<right; i++) { res.add(matrix[top][i]); } for (int i=top; i<bottom; i++) { res.add(matrix[i][right]); } for (int i=right; i>left; i--) { res.add(matrix[bottom][i]); } for (int i=bottom; i>top; i--) { res.add(matrix[i][left]); } top++; right--; bottom--; left++; } if(top == bottom) { for (int i=left; i<=right; i++) res.add(matrix[top][i]); }else if(left == right) { for (int i=top; i<= bottom; i++) { res.add(matrix[i][left]); } } int[] result = new int[res.size()]; for (int i=0; i<res.size(); i++) { result[i] = res.get(i).intValue(); } return result; }
|