代码随想录算法训练营第二天| 209. 长度最小的子数组、 59.螺旋矩阵II
209. 长度最小的子数组
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int size = nums.size();
if (size == 0) {
return 0;
}
if (size == 1) {
return nums[0] >= target ? 1 : 0;
}
int i = 0, j = 0;
int sum = 0;
int minNum = INT_MAX;
while (j < size) {
sum += nums[j];
j++;
while (i < size && sum >= target) {
sum -= nums[i];
minNum = min(minNum, j - i);
i++;
}
}
if(minNum == INT_MAX){
return 0;
}
return minNum;
}
};
没有难度,但是代码不够优雅,后续有时间应该优化
59.螺旋矩阵II
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n));
int curValue = 1;
int i = -1, j = 0;
int maxVal = n - 1;
while (curValue <= n * n) {
while (i < maxVal) {
ans[j][++i] = curValue++;
}
while (j < maxVal) {
ans[++j][i] = curValue++;
}
while (i > n - maxVal -1) {
ans[j][--i] = curValue++;
}
while (j > n - maxVal) {
ans[--j][i] = curValue++;
}
maxVal--;
}
return ans;
}
};
看题解后ac