25期代码随想录算法训练营第二天 | 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II

目录

977.有序数组的平方

链接

思路

双指针。

数组平方的最大值就在数组的两端,不是最左边就是最右边。所以我们可以用一左一右两个指针,来获取最大值,再放入到我们的结果集。

代码

python 复制代码
class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        l, r, i = 0, len(nums) - 1, len(nums) - 1
        res = [0 for _ in range(len(nums))]
        while l <= r:
            if nums[l] ** 2 < nums[r] ** 2:
                res[i] = nums[r] ** 2
                r -= 1
            else:
                res[i] = nums[l] ** 2
                l += 1
            i -= 1
        return res

209.长度最小的子数组

链接

滑动窗口

代码

python 复制代码
class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        l, r, i = 0, len(nums) - 1, len(nums) - 1
        res = [0 for _ in range(len(nums))]
        while l <= r:
            if nums[l] ** 2 < nums[r] ** 2:
                res[i] = nums[r] ** 2
                r -= 1
            else:
                res[i] = nums[l] ** 2
                l += 1
            i -= 1
        return res

59.螺旋矩阵II

链接

代码

python 复制代码
class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        res = [[0] * n for _ in range(n)]
        startx, starty = 0, 0
        loop, mid = n // 2, n // 2
        count = 1
        
        for offset in range(1, loop + 1):
            #upper left to right
            for i in range(starty, n - offset):
                res[startx][i] = count
                count += 1
            
            #up to bottom
            for i in range(startx, n - offset):
                res[i][n - offset] = count
                count += 1

            # from bottom right to left
            for i in range(n - offset, starty, -1):
                res[n - offset][i] = count
                count += 1
            
            # from bottom to up
            for i in range(n - offset, startx, -1):
                res[i][starty] = count
                count += 1
            
            startx += 1
            starty += 1
        
        if n % 2 != 0:
            res[mid][mid] = count

        return res
相关推荐
qq_589568102 分钟前
现代 Linux 系统(如 Ubuntu 24.04、Debian 12+) pip 安装第三方包报错解决
python·ubuntu
从负无穷开始的三次元代码生活14 分钟前
算法零碎灵感点分享
算法
染指111019 分钟前
9.LangChain框架(实现RAG)
数据库·人工智能·算法·机器学习·ai·大模型
大数据三康25 分钟前
在spyder进行的遗传算法练习
开发语言·python·算法
Gene_202229 分钟前
轮式底盘的微分平坦
算法
医用门40 分钟前
医院用门一线品牌
leetcode
吴佳浩1 小时前
现代多模态大模型的核心基础:Unified Self-Attention
人工智能·算法·llm
njsgcs1 小时前
我仓库内cad python 有哪些应用到聚类的方法
开发语言·python·聚类
web3.08889992 小时前
电商数据化运营:速卖通API+Python打造竞品监控与选品利器
开发语言·python