【代码随想录算法训练营第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

相关推荐
zycoder.2 分钟前
力扣面试经典150题day3第五题(lc69),第六题(lc189)
算法·leetcode·面试
_dindong7 小时前
基础算法:滑动窗口
数据结构·学习·算法·leetcode·力扣
nju_spy11 小时前
力扣每日一题(二)任务安排问题 + 区间变换问题 + 排列组合数学推式子
算法·leetcode·二分查找·贪心·排列组合·容斥原理·最大堆
代码对我眨眼睛11 小时前
226. 翻转二叉树 LeetCode 热题 HOT 100
算法·leetcode·职场和发展
黑色的山岗在沉睡12 小时前
LeetCode 494. 目标和
算法·leetcode·职场和发展
小欣加油1 天前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗1 天前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗1 天前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展
Mr.Ja1 天前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器
微笑尅乐1 天前
从暴力到滑动窗口全解析——力扣8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展