LeetCode - 解题笔记 - 54 - Spiral Matrix

本文探讨了一种高效的算法Solution1,利用分治思想解决SpiralMatrix问题,以递归的方式按层次读取矩阵,确保时间复杂度为O(N)且空间复杂度为O(1)。通过实例和Python代码展示如何按顺时针顺序遍历矩阵并返回结果。
摘要由CSDN通过智能技术生成

Spiral Matrix

Solution 1

此题也是一个模拟题。利用分治的思想,对于整个矩阵,按照层次进行划分,这样每一层的数据读取顺序是一致的,这样就能够实现更好的代码复用。其中每一个“层”就是矩阵的一整个圈,读取顺序通过记录上下行和左右列的位置,并按照旋转方向进行读取。

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入矩阵的元素个数,算法中仅遍历所有元素一次
  • 空间复杂度: O ( 1 ) O(1) O(1),不考虑输出数据结构,仅维护常数个状态变量
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        auto ans = vector<int>();
        
        int top = 0, bottom = matrix.size() - 1;
        int left = 0, right = matrix[0].size() - 1;
        
        while (top <= bottom && left <= right) {
            // top-left to top-right
            for (int index = left; index <= right; ++index) { ans.emplace_back(matrix[top][index]); }
            // top-right to bottom-right
            for (int index = top + 1; index <= bottom; ++index) { ans.emplace_back(matrix[index][right]); }
            
            // 单数情形判定,只有一行或者一列
            if (top < bottom && left < right) {
                // bottom-right to bottom-left
                for (int index = right - 1; index >= left; --index) { ans.emplace_back(matrix[bottom][index]); }
                // bottom-left to top-left
                for (int index = bottom - 1; index > top; --index) { ans.emplace_back(matrix[index][left]); }
            }
                
            top++, bottom--;
            left++, right--;
        }
        
        return ans;
    }
};

Solution 2

Solution 1的Python实现

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        ans = list()
        
        top, left = 0, 0
        bottom, right = len(matrix) - 1, len(matrix[0]) - 1
        
        while top <= bottom and left <= right:
            for index in range(left, right + 1): ans.append(matrix[top][index])
            for index in range(top + 1, bottom + 1): ans.append(matrix[index][right])
                
            if top < bottom and left < right:
                for index in range(right - 1, left - 1, -1): ans.append(matrix[bottom][index])
                for index in range(bottom - 1, top, -1): ans.append(matrix[index][left])
                    
            top += 1
            bottom -= 1
            left += 1
            right -= 1
            
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值