977.有序数组的平方
题目链接https://leetcode.cn/problems/squares-of-a-sorted-array/description/
-
题解:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortedSquares(int* nums, int numsSize, int* returnSize) {
//返回数组的大小和传入数组的大小相同
*returnSize = numsSize;
int* result = (int*)malloc(sizeof(int)*numsSize);
int right = numsSize - 1;
int left = 0;
for(int index = numsSize - 1;index >= 0;index --){
int leftResult = nums[left] * nums[left];
int rightResult = nums[right] * nums[right];
if(leftResult > rightResult){
result[index] = leftResult;
left ++;
}else{
result[index] = rightResult;
right --;
}
}
return result;
}
209.长度最小的子数组
题目链接https://leetcode.cn/problems/minimum-size-subarray-sum/description/
-
题解:
int minSubArrayLen(int target, int* nums, int numsSize) {
//初始化长度最小的子数组长度为最大值,便于得到最小长度
int result = INT_MAX;
int sum = 0;
//双指针法求最短数组长度
int left = 0;
int right = 0;
//以右指针遍历数组尾部
for(; right < numsSize ; right ++){
sum += nums[right];
//当sum值>=target,收缩右边界并保存当前长度,以便每次更新最短长度
while(sum >= target){
int temp = right - left + 1;
result = result < temp ? result : temp;
sum -= nums[left ++];
}
}
return result == INT_MAX ? 0 : result;
}
59.螺旋矩阵II
题目链接https://leetcode.cn/problems/spiral-matrix-ii/description/
-
题解:
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) {
//tips:
*returnSize = n;
*returnColumnSizes = (int*)malloc(sizeof(int) * n);
//初始化返回结果数组result,一级指针(行)
int** result = (int**)malloc(sizeof(int*) * n);
//初始化二级指针
for(int i = 0; i < n; i ++){
result[i] = (int*)malloc(sizeof(int) * n);
//tips:
(*returnColumnSizes)[i] = n;
}
//设置循环起始位置
int startX = 0;
int startY = 0;
int offset = 1;
int count = 1;
//可能的奇数圈的中间的填充位置
int middle = n / 2;
//控制转大圈
int loop = n / 2;
while(loop){
int i = startX;
int j = startY;
for(;j < n - offset; j++){
result[i][j] = count++;
}
for(;i < n - offset; i++){
result[i][j] = count++;
}
for(;j > startY; j--){
result[i][j] = count++;
}
for(;i > startX; i--){
result[i][j] = count++;
}
offset++;
startX++;
startY++;
loop--;
}
//若为奇数,填充最后的元素
if(n % 2){
result[middle][middle] = count;
}
return result;
}