【代码随想录算法训练营第37期 第二天 | LeetCode977.有序数组的平方、209.长度最小的子数组、59.螺旋矩阵II】
代码随想录算法训练营第37期 第二天 | LeetCode977.有序数组的平方、209.长度最小的子数组、59.螺旋矩阵II
一、977.有序数组的平方
解题代码C++:
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.%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E7%9A%84%E5%B9%B3%E6%96%B9.html
二、209.长度最小的子数组
解题代码C++:
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.%E9%95%BF%E5%BA%A6%E6%9C%80%E5%B0%8F%E7%9A%84%E5%AD%90%E6%95%B0%E7%BB%84.html
三、59.螺旋矩阵II
解题代码C++:
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.%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5II.html
原文地址:https://blog.csdn.net/cattte/article/details/138586999
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!