LeetCode - 解题笔记 - 59 - Spiral Matrix II

Spiral Matrix II

Solution 1

可以直接使用Spiral Matrix的题目进行改动即可。原问题沿着指定的路线读取输入矩阵的数据,现在这个问题就是按照这个路径给矩阵赋值,从1开始沿着步数增长。

  • 时间复杂度: O ( N 2 ) O(N^2) O(N2),其中 N N N为输入的数字,遍历整个矩阵
  • 空间复杂度: O ( 1 ) O(1) O(1),在不考虑输出占用的情况下,仅维护常数个状态变量
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        auto ans = vector<vector<int>>(n, vector<int>(n, 0));
        
        int top = 0, bottom = n - 1;
        int left = 0, right = n - 1;
        
        int tag = 1;
        while (top <= bottom && left <= right) {
            // top-left to top-right
            for (int index = left; index <= right; ++index) { ans[top][index] = tag++; }
            // top-right to bottom-right
            for (int index = top + 1; index <= bottom; ++index) { ans[index][right] = tag++; }
            
            // 单数情形判定,只有一行或者一列
            if (top < bottom && left < right) {
                // bottom-right to bottom-left
                for (int index = right - 1; index >= left; --index) { ans[bottom][index] = tag++; }
                // bottom-left to top-left
                for (int index = bottom - 1; index > top; --index) { ans[index][left] = tag++; }
            }
                
            top++, bottom--;
            left++, right--;
        }
        
        return ans;
    }
};

Solution 2

Solution 1的Python实现,注意Python对list的实例化的方式。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值