代码随想录day02
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
- 双指针
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int l = 0, r = 0;
int sum = 0;
int res = 100010;
for (r = 0; r < nums.size(); r ++)
{
sum += nums[r];
while (sum >= target)
{
res = min(res, r - l + 1);
sum -= nums[l ++];
}
}
return res == 100010 ? 0 : res;
}
};
- 二分+前缀和
因为问题具有二分性(当长度小于所求数组的长度时,不可能有结果,反之则一定有),所以可以用二分解决。
在计算区间和为了避免多次循环,可以用前缀和优化
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int N = nums.size();
vector<int> s(N+1, 0);
for (int i = 1; i <= N; i ++) s[i] += (s[i-1] + nums[i-1]);
int l = 0, r = nums.size();
while (l < r)
{
int mid = l + r >> 1;
bool isf = false;
for (int j = mid; j <= N; j ++)
{
if (s[j] - s[j-mid] >= target)
{
isf = true;
break;
}
}
if (isf) r = mid;
else l = mid + 1;
}
if (l == N) return s[N] >= target ? N : 0;
else return l;
}
};
59. 螺旋矩阵 II
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
输入:n = 1
输出:[[1]]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int x = 0, y = 0;
vector<vector<int>> res(n, vector<int>(n));
int cnt = n;
int num = 1;
int loop = n/2;
int std = 0;
while(loop --)
{
x = std, y = std;
for (int i = 1; i < cnt; i ++) res[x][y ++] = num ++;
for (int i = 1; i < cnt; i ++) res[x ++][y] = num ++;
for (int i = 1; i < cnt; i ++) res[x][y --] = num ++;
for (int i = 1; i < cnt; i ++) res[x --][y] = num ++;
cnt -= 2;
std ++;
}
if (n % 2 != 0) res[n/2][n/2] = num;
return res;
}
};