標籤:put row leetcode 過程 round 一個 ++ arraylist return
題目:螺旋矩陣
難度:Medium
題目內容:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
翻譯:
給定一個m x n元素的矩陣(m行,n列),以順時針螺旋順序返回矩陣的所有元素。
Example 1:
Input:[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]Output: [1,2,3,6,9,8,7,4,5]
Example 2:
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]
我的思路:因為每一圈都是由四條邊組成的,所以寫一個while死迴圈,裡面有四個for迴圈,每個for迴圈結束之後都將相應的指標減少,同時判斷是否超標,超標就退出。
eg:
while (true) {
// 橫著 for add
// top ++
// top 是否小於bottom 是則break
。。。
}
My Code:
1 public List<Integer> spiralOrder(int[][] matrix) { 2 List<Integer> res = new ArrayList<Integer>(); 3 if(matrix.length == 0 || matrix[0].length == 0) return res; 4 5 int top = 0; 6 int bottom = matrix.length-1; 7 int left = 0; 8 int right = matrix[0].length-1; 9 10 while(true){11 for(int i = left; i <= right; i++) res.add(matrix[top][i]);12 top++;13 if(left > right || top > bottom) break;14 15 for(int i = top; i <= bottom; i++) res.add(matrix[i][right]);16 right--;17 if(left > right || top > bottom) break;18 19 for(int i = right; i >= left; i--) res.add(matrix[bottom][i]);20 bottom--;21 if(left > right || top > bottom) break;22 23 for(int i = bottom; i >= top; i--) res.add(matrix[i][left]);24 left++;25 if(left > right || top > bottom) break;26 }27 28 return res;29 }
我的複雜度:O(N * M) 行乘以列
編碼過程中的問題:
1、沒有注意到當輸入為空白的數組的時候 right 和bottom都會取成負數,所以得加上判空。
答案代碼:
和我一樣的。
LeetCode第[54]題(Java):Spiral Matrix