依旧是进营前刷过的题目,代码如下:
1. 977 有序数组的平方
int* sortedSquares(int* nums, int numsSize, int* returnSize) {
*returnSize = numsSize;
int left = 0, right = numsSize - 1;
int *ans = (int *)malloc(sizeof(int) * numsSize);
int index;
for(index = numsSize - 1; index>=0; index--)
{
int lsqr = nums[left] * nums[left];
int rsqr = nums[right] * nums[right];
if(lsqr >= rsqr)
{
ans[index] = lsqr;
left++;
}
else
{
ans[index] = rsqr;
right--;
}
}
return ans;
}
2. 209.长度最小的子数组
int minSubArrayLen(int target, int* nums, int numsSize) {
int result = INT32_MAX;
int i = 0, j = 0;
int sum = 0, subL = 0;
for(j = 0; j < numsSize; j++)
{
sum += nums[j];
while(sum >= target)
{
subL = j - i + 1;
result = result > subL? subL: result;
sum -= nums[i++];
}
}
return result == INT32_MAX? 0: result;
}
3. 59.螺旋矩阵II
这道题目主要是要找好赋值的时候哪些值是不变量,以及边界开闭的一致性。
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) {
int** matrix = (int**) malloc(sizeof(int*) * n);
*returnColumnSizes = malloc(sizeof(int) * n);
(*returnSize) = n;
int num = 1, offset = 1;
int loop = n/2;
int mid = n/2;
int startx = 0, starty = 0;
int i, j;
for(i = 0; i < n; i++)
{
(*returnColumnSizes)[i] = n;
matrix[i] = (int*)malloc(sizeof(int) * n);
}
while(loop--)
{
i = startx;
j = starty;
for(j = starty; j < n - offset; j++)
{
matrix[startx][j] = num++;
}
for(i = startx; i < n - offset; i++)
{
matrix[i][j] = num++;
}
for(; j > starty; j--)
{
matrix[i][j] = num++;
}
for(; i > startx; i--)
{
matrix[i][j] = num++;
}
startx++;
starty++;
offset++;
}
if(n%2)
matrix[mid][mid] = num;
return matrix;
}