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
相关推荐
xinxiyinhe13 分钟前
如何设置Cursor中.cursorrules文件
人工智能·python
roman_日积跬步-终至千里18 分钟前
【后端基础】布隆过滤器原理
算法·哈希算法
若兰幽竹32 分钟前
【机器学习】多元线性回归算法和正规方程解求解
算法·机器学习·线性回归
诸神缄默不语39 分钟前
如何用Python 3自动打开exe程序
python·os·subprocess·python 3
鱼力舟1 小时前
【hot100】240搜索二维矩阵
算法
橘子师兄1 小时前
分页功能组件开发
数据库·python·django
Logintern091 小时前
使用VS Code进行Python编程的一些快捷方式
开发语言·python
Multiple-ji2 小时前
想学python进来看看把
开发语言·python
liuyuzhongcc2 小时前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
北_鱼2 小时前
支持向量机(SVM):算法讲解与原理推导
算法·机器学习·支持向量机