LeetCode 59. 螺旋矩阵 II && LeetCode 54. 螺旋矩阵
发布日期:2021-07-01 03:13:57 浏览次数:2 分类:技术文章

本文共 3144 字,大约阅读时间需要 10 分钟。

文章目录

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 解题

类似题目:

  • 创建变量top、bottom表示上下行的区间,left、right表示列的区间
    在这里插入图片描述
class Solution {
public: vector
> generateMatrix(int n) {
vector
> v(n, vector
(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
spiralOrder(vector
>& matrix) {
if(matrix.empty()) return {
}; vector
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

class Solution {
//2020.2.22public: vector
spiralOrder(vector
>& 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
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; }};

在这里插入图片描述

转载地址:https://michael.blog.csdn.net/article/details/100395555 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 35. 搜索插入位置(二分查找)
下一篇:LeetCode 61. 旋转链表

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月28日 05时50分39秒