LeetCode第[54]題(Java):Spiral Matrix

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.