日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > java >内容正文

java

【LeetCode-面试算法经典-Java实现】【054-Spiral Matrix(螺旋矩阵)】

發(fā)布時(shí)間:2024/4/15 java 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode-面试算法经典-Java实现】【054-Spiral Matrix(螺旋矩阵)】 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

【054-Spiral Matrix(螺旋矩陣)】


【LeetCode-面試算法經(jīng)典-Java實(shí)現(xiàn)】【全部題目文件夾索引】

原題

  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].

題目大意

  給定一個(gè)m*n的矩陣。輸入全部元素的螺旋順序。

解題思路

  使用計(jì)算輸出的方法,先處理上面一行。再處理右邊一列。再處理以下一行,再處理左邊一列,一直這樣操作,直到全部的元素都處理完。


代碼實(shí)現(xiàn)

算法實(shí)現(xiàn)類(lèi)

import java.util.ArrayList; import java.util.List;public class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> result = new ArrayList<>(50);if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {return result;}// 僅僅有一行的情況if (matrix.length == 1) {for (int i : matrix[0]) {result.add(i);}return result;}// 僅僅有一列的情況if (matrix[0].length == 1) {for (int i = 0; i < matrix.length; i++) {result.add(matrix[i][0]);}return result;}// 計(jì)算有多少圈int row = matrix.length;int col = matrix[0].length;int cycle = row < col ?

row : col; cycle = (cycle + 1) / 2; int round = 0; // 記錄當(dāng)前是第幾圈 int left = 0; int right = matrix[0].length - 1; int top = 0; int down = matrix.length - 1; int total = col*row; int count = 0; while (round < cycle) { // 上面一行 for (int i = left; i <= right && count < total; i++) { count++; result.add(matrix[round][i]); } top++; // // 右邊一列 for (int i = top; i <= down && count < total; i++) { count++; result.add(matrix[i][col - round - 1]); } right--; // 底下一行 for (int i = right; i >= left && count < total; i--) { count++; result.add(matrix[row - round - 1][i]); } down--; // 左邊一列 for (int i = down; i >= top && count < total; i--) { count++; result.add(matrix[i][round]); } left++; round++; } return result; } }

評(píng)測(cè)結(jié)果

  點(diǎn)擊圖片,鼠標(biāo)不釋放,拖動(dòng)一段位置,釋放后在新的窗體中查看完整圖片。

特別說(shuō)明

歡迎轉(zhuǎn)載,轉(zhuǎn)載請(qǐng)注明出處【http://blog.csdn.net/derrantcm/article/details/47120491】

轉(zhuǎn)載于:https://www.cnblogs.com/jzdwajue/p/7103307.html

總結(jié)

以上是生活随笔為你收集整理的【LeetCode-面试算法经典-Java实现】【054-Spiral Matrix(螺旋矩阵)】的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。