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
相关推荐
203号居民4 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean21035 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
触底反弹5 小时前
面试被问到 Text2SQL,我用 DeepSeek 自己实现了一个
python·sqlite
Nil2085 小时前
leetcode 78子集
数据结构·算法·leetcode
2601_962295585 小时前
python+selenium实现自动化测试
自动化测试·python·selenium·学习心得·web端测试
青 春 记 忆5 小时前
零基础入门python66:FastAPI AI标题、摘要和标签
python·fastapi·后端开发
qq_22589174665 小时前
基于Python+Django的LangGraph智能旅游规划系统
python·django·旅游
青 春 记 忆6 小时前
零基础入门python65:FastAPI 安全调用大模型API
python·fastapi·后端开发
en.en..6 小时前
Linux fork() 工作原理
数据结构·算法
维克兜率天6 小时前
【维克】特征归一化与标准化:为什么模型对数据的“尺度“很敏感?
人工智能·笔记·python·机器学习·量化