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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 59. 螺旋矩阵 II LeetCode 54. 螺旋矩阵

發布時間:2024/7/5 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 59. 螺旋矩阵 II LeetCode 54. 螺旋矩阵 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 1. 題目信息
    • 2. LeetCode 59 解題
    • 3. LeetCode 54. 螺旋矩陣
    • 4.《劍指Offer》面試題29

1. 題目信息

給定一個正整數 n,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。

示例:輸入: 3 輸出: [[ 1, 2, 3 ],[ 8, 9, 4 ],[ 7, 6, 5 ] ]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. LeetCode 59 解題

類似題目:LeetCode 885. 螺旋矩陣 III

  • 創建變量top、bottom表示上下行的區間,left、right表示列的區間
class Solution { public:vector<vector<int>> generateMatrix(int n) {vector<vector<int> > v(n, vector<int>(n,0));if(n == 0) return {};int i, num = 0, total = n*n, top = 0, bottom = n-1, left = 0, right = n-1;while(num < total){for(i = left; i <= right; ++i)v[top][i] = ++num;++top;for(i = top; i <= bottom; ++i)v[i][right] = ++num;--right;for(i = right; i >= left; --i)v[bottom][i] = ++num;--bottom;for(i = bottom; i >= top; --i)v[i][left] = ++num;++left;}return v;} };

3. LeetCode 54. 螺旋矩陣

給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

class Solution { public:vector<int> spiralOrder(vector<vector<int>>& matrix) {if(matrix.empty()) return {};vector<int> ans;int m = matrix.size(), n = matrix[0].size();int i, num = 0, total = m*n, top = 0, bottom = m-1, left = 0, right = n-1;while(num < total){for(i = left; i <= right; ++i)ans.push_back(matrix[top][i]),num++;if(num == total)break;++top;for(i = top; i <= bottom; ++i)ans.push_back(matrix[i][right]),num++;if(num == total)break;--right;for(i = right; i >= left; --i)ans.push_back(matrix[bottom][i]),num++;if(num == total)break;--bottom;for(i = bottom; i >= top; --i)ans.push_back(matrix[i][left]),num++;if(num == total)break;++left;}return ans;} };

4.《劍指Offer》面試題29

面試題29. 順時針打印矩陣

class Solution { //2020.2.22 public:vector<int> spiralOrder(vector<vector<int>>& matrix) {if(matrix.size()==0 || matrix[0].size()==0)return {};int i = 0, k = 0, count = matrix.size()*matrix[0].size();int left = 0, right = matrix[0].size()-1, up = 0, bottom = matrix.size()-1;vector<int> ans(count);while(count){i = left;while(count && i <= right){ans[k++] = matrix[up][i++];count--;}up++,i = up;while(count && i <= bottom){ans[k++] = matrix[i++][right];count--;}right--;i = right;while(count && i >= left){ans[k++] = matrix[bottom][i--];count--;}bottom--;i = bottom;while(count && i >= up){ans[k++] = matrix[i--][left];count--;}left++;}return ans;} };

總結

以上是生活随笔為你收集整理的LeetCode 59. 螺旋矩阵 II LeetCode 54. 螺旋矩阵的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。