题目:
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]
.
链接:https://leetcode.com/problems/spiral-matrix/#/description
4/19/2017
3ms, 27%
自己不会,抄别人的
思路是保存4个边界,每次循环完更新边界值,并且检查总的输出量。
第8行的判断可以用过left <= right, top <= bottom来检查
1 public class Solution { 2 public List<Integer> spiralOrder(int[][] matrix) { 3 List<Integer> ret = new ArrayList<Integer>(); 4 if (matrix.length == 0 || matrix[0].length == 0) return ret; 5 int count = matrix.length * matrix[0].length; 6 int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1; 7 8 while (count > 0) { 9 for (int i = left; i <= right; i++) { 10 ret.add(matrix[top][i]); 11 count--; 12 } 13 top++; 14 if (count > 0) { 15 for (int i = top; i <= bottom; i++) { 16 ret.add(matrix[i][right]); 17 count--; 18 } 19 right--; 20 } 21 if (count > 0) { 22 for (int i = right; i >= left; i--) { 23 ret.add(matrix[bottom][i]); 24 count--; 25 } 26 bottom--; 27 } 28 if (count > 0) { 29 for (int i = bottom; i >= top; i--) { 30 ret.add(matrix[i][left]); 31 count--; 32 } 33 top++; 34 } 35 } 36 return ret; 37 } 38 }
https://discuss.leetcode.com/topic/3713/super-simple-and-easy-to-understand-solution
更多讨论: