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

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


一、977.有序数组的平方

解题代码C++:

cpp 复制代码
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int len = nums.size();

        for(int i = 0; i < len; i ++)
            nums[i] = nums[i] * nums[i];
        
        sort(nums.begin(), nums.end());

        return nums;
    }
};

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0977.有序数组的平方.html



二、209.长度最小的子数组

解题代码C++:

cpp 复制代码
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int len = nums.size();

        int sum = 0, k = len + 5;
        for(int i = 0, j = 0; i < len; i ++)
        {
            sum += nums[i];

            while(sum >= target && j <= i)
            {
                sum -= nums[j];
                j ++;

                if(sum < target) k = min(k, i - j + 2);
            }
        }

        if(k == len + 5) return 0;
        else return k;
    }
};

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0209.长度最小的子数组.html



三、59.螺旋矩阵II

解题代码C++:

cpp 复制代码
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        vector<vector<int>> res(n, vector<int>(n));

        for(int k = 1, x = 0, y = 0, d = 0; k <= n * n; k ++)
        {
            res[x][y] = k;

            int a = x + dx[d], b = y + dy[d];

            if(a >= n || a < 0 || b >= n || b < 0 || res[a][b])
            {
                d = (d + 1) % 4;
                a = x + dx[d];
                b = y + dy[d];
            }

            x = a, y = b;
        }

        return res;
    }
};

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0059.螺旋矩阵II.html

相关推荐
Maỿbe8 分钟前
力扣hot图论部分
算法·leetcode·图论
LYFlied16 分钟前
【每日算法】LeetCode 78. 子集
数据结构·算法·leetcode·面试·职场和发展
月明长歌20 分钟前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树
鹿角片ljp21 分钟前
力扣234.回文链表-反转后半链表
算法·leetcode·链表
(●—●)橘子……22 分钟前
记力扣1471.数组中的k个最强值 练习理解
数据结构·python·学习·算法·leetcode
LYFlied38 分钟前
【算法解题模板】-【回溯】----“试错式”问题解决利器
前端·数据结构·算法·leetcode·面试·职场和发展
Code Slacker1 小时前
LeetCode Hot100 —— 普通数组(面试纯背版)(五)
数据结构·c++·算法·leetcode·面试
sin_hielo1 小时前
leetcode 3573(买卖股票问题,状态机dp)
数据结构·算法·leetcode
flashlight_hi1 小时前
LeetCode 分类刷题:110. 平衡二叉树
javascript·算法·leetcode
patrickpdx2 小时前
leetcode:环形链表
算法·leetcode·链表