牛客-螺旋矩阵

题目

描述
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
数据范围:
0≤n,m≤10,矩阵中任意元素都满足 ∣val∣≤100
要求:空间复杂度 O(nm) ,时间复杂度 O(nm)

思路

从外围走,从左到右,从上到下,从右到左,从下到上。每走一下更新边界,直到left和right或者top和bottom重合时跳出循环。

代码

python版本:

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param matrix int整型二维数组 
# @return int整型一维数组
#
class Solution:
    def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
        # write code here
        storage = []
        if not len(matrix):
            return storage
        left =0
        right = len(matrix[0])
        top=0
        bottom = len(matrix)
        while(left<right and top<bottom):
            #从左到右
            for i in range(left, right):
                storage.append(matrix[top][i])
            top += 1
            if(top==bottom):
                break
            #从上到下
            for i in range(top, bottom):
                storage.append(matrix[i][right-1])
            right -= 1
            if(left == right):
                break
            #从右到左
            for i in range(right-1, left-1, -1):
                storage.append(matrix[bottom-1][i])
            bottom -= 1
            if(top==bottom):
                break
            #从下到上
            for i in range(bottom-1, top-1, -1):
                storage.append(matrix[i][left])
            if(left == right):
                break
            left += 1
        return storage

c++版本:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> storage;
        if(matrix.empty()){
            return storage;
        }
        int top = 0;
        int bottom = matrix.size();
        int left = 0;
        int right = matrix[0].size();
        while(left<right && top<bottom){
            //从左到右
            for(int i=left; i<right; i++){
                storage.push_back(matrix[top][i]);
            }
            top++;
            if(top==bottom){
                break;
            }
            //从上到下
            for(int i=top; i<bottom; i++){
                storage.push_back(matrix[i][right-1]);
            }
            right--;
            if(left==right){
                break;
            }
            //从右到左
            for(int i=right-1; i>=left; i--){
                storage.push_back(matrix[bottom-1][i]);
            }
            bottom--;
            //从下到上
            for(int i=bottom-1; i>=top; i--){
                storage.push_back(matrix[i][left]);
            }
            left++;
        }
        return storage;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超超爱AI

土豪请把你的零钱给我点

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值