代码随想录算法训练营第42期 第二天 | LeetCode977.有序数组的平方、209.长度最小的子数组、59.螺旋矩阵II
一、977.有序数组的平方
解题代码C:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortedSquares(int* nums, int numsSize, int* returnSize) {
*returnSize = numsSize;
int right = numsSize - 1;
int left = 0;
int* ans = (int*)malloc(sizeof(int) * numsSize);
int index;
for(index = numsSize - 1; index >= 0; index --)
{
int lSquare = nums[left] * nums[left];
int rSquare = nums[right] * nums[right];
if(lSquare > rSquare)
{
ans[index] = lSquare;
left ++;
}
else
{
ans[index] = rSquare;
right --;
}
}
return ans;
}
题目链接/文章讲解/视频讲解:
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:
int minSubArrayLen(int target, int* nums, int numsSize) {
int minLength = INT_MAX;
int sum = 0;
int left = 0, right = 0;
for(; right < numsSize; right ++)
{
sum += nums[right];
while(sum >= target)
{
int subLength = right - left + 1;
minLength = minLength < subLength ? minLength : subLength;
sum -= nums[left ++];
}
}
return minLength == INT_MAX ? 0 : minLength;
}
题目链接/文章讲解/视频讲解:
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:
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
//初始化返回的结果数组的大小
*returnSize = n;
*returnColumnSizes = (int*)malloc(sizeof(int) * n);
//初始化返回结果数组ans
int** ans = (int**)malloc(sizeof(int*) * n);
int i;
for(i = 0; i < n; i++) {
ans[i] = (int*)malloc(sizeof(int) * n);
(*returnColumnSizes)[i] = n;
}
//设置每次循环的起始位置
int startX = 0;
int startY = 0;
//设置二维数组的中间值,若n为奇数。需要最后在中间填入数字
int mid = n / 2;
//循环圈数
int loop = n / 2;
//偏移数
int offset = 1;
//当前要添加的元素
int count = 1;
while(loop) {
int i = startX;
int j = startY;
//模拟上侧从左到右
for(; j < startY + n - offset; j++) {
ans[startX][j] = count++;
}
//模拟右侧从上到下
for(; i < startX + n - offset; i++) {
ans[i][j] = count++;
}
//模拟下侧从右到左
for(; j > startY; j--) {
ans[i][j] = count++;
}
//模拟左侧从下到上
for(; i > startX; i--) {
ans[i][j] = count++;
}
//偏移值每次加2
offset+=2;
//遍历起始位置每次+1
startX++;
startY++;
loop--;
}
//若n为奇数需要单独给矩阵中间赋值
if(n%2)
ans[mid][mid] = count;
return ans;
}
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0059.%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5II.html