Leecode-209-长度最小的子数组
题目
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其总和大于等于 target 的长度最小的 连续
子数组
[numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例
示例1
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例2
输入:target = 4, nums = [1,4,4]
输出:1
示例3
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
解题思路
这道题可以使用滑动窗口
的方法实现
- 首先定义两个指针
left
和right
,left表示起始位置,right表示终止位置,均初始化为零 - 定义变量
sum
,用来存储元素和 - 通过for循环遍历,把下标为right的元素值赋给sum
- 判断若sum大于等于目标值target,进入while循环,更新返回值returnSize,并让sum减去下标为初始位置的元素,移动初始位置
- 使用三目运算符判断若没有进入while循环,则returnSize值不改变,即所有元素之和小于target目标值,返回零,否则,返回returnSize
代码实现
int minSubArrayLen(int target, int* nums, int numsSize) {
int returnSize = numsSize + 1;
int left = 0,right = 0;
int sum = 0;
for(;right < numsSize; right++){
sum += nums[right];
while(sum >= target){
int minSize = right - left + 1;
returnSize = minSize<returnSize ? minSize : returnSize;
sum -= nums[left];
left++;
}
}
return returnSize = returnSize!=numsSize+1 ? returnSize : 0;
}
Leecode-59-螺旋矩阵II
题目
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。## 示例
示例1
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例2
输入:n = 1
输出:[[1]]
解题思路
-
初始化返回的结果数组的大小
returnSize
和返回结果数组nums
-
设置每次循环的起始位置
starti
、startj
和偏移数offset
,count
是每次要添加的元素,mid
记录矩阵最中间的元素,loop
是循环圈数 -
模拟顺时针画矩阵
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
-
移动起始位置和偏移值
-
若n为奇数需要单独给矩阵中间赋值
代码实现
/**
* 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) {
*returnSize = n;
*returnColumnSizes = (int*)malloc(sizeof(int) * n);
int **nums = (int **)malloc(sizeof(int*)*n);
for(int i = 0; i < n; i++) {
nums[i] = (int*)malloc(sizeof(int) * n);
(*returnColumnSizes)[i] = n;
}
int mid = n/2; //n为奇数时最中间的元素下标
int count = 1; //要添加的元素
int starti = 0,startj = 0;//每次循环起始位置
int offset = 1; //偏移数
int loop = n/2; //循环圈数
while(loop){
int i = starti, j = startj;
for(; j < startj + n - offset; j++){
nums[starti][j] = count++;
}
for(; i < starti + n - offset; ){
nums[i++][j] = count++;
}
for(; j > startj; ){
nums[i][j--] = count++;
}
for(; i > starti; ){
nums[i--][j] = count++;
}
starti++;
startj++;
offset+=2;
loop--;
}
if(n%2){
nums[mid][mid] = count;
}
return nums;
}