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
相关推荐
FL16238631296 小时前
[yolov11改进系列]基于yolov11使用fasternet_t0替换backbone用于轻量化网络的python源码+训练源码
python·yolo·php
Freshman小白6 小时前
python算法打包为docker镜像(边缘端api服务)
python·算法·docker
岁岁岁平安6 小时前
python mysql-connector、PyMySQL基础
python·mysql·pymysql
mit6.8247 小时前
[VT-Refine] Simulation | Fine-Tuning | docker/run.sh
算法
朴shu7 小时前
Delta数据结构:深入剖析高效数据同步的奥秘
javascript·算法·架构
铁锹少年7 小时前
当多进程遇上异步:一次 Celery 与 Async SQLAlchemy 的边界冲突
分布式·后端·python·架构·fastapi
梨轻巧7 小时前
pyside6常用控件:QCheckBox() 单个复选框、多个复选框、三态模式
python
寒秋丶7 小时前
Milvus:集合(Collections)操作详解(三)
数据库·人工智能·python·ai·ai编程·milvus·向量数据库
寒秋丶7 小时前
Milvus:Schema详解(四)
数据库·人工智能·python·ai·ai编程·milvus·向量数据库
mit6.8247 小时前
博弈dp|凸包|math分类
算法