209.长度最小的子数组
这道题用了滑动区间
做的很不顺利
明天再温习一遍
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int i = 0;
int result = INT32_MAX;
int sum = 0;
int subL = 0;
for(int j = 0; j < nums.size(); j++){
sum += nums[j];
while(sum >= target){
subL = j - i + 1;
sum -= nums[i++];
result = min(subL, result);
}
}
return result == INT32_MAX? 0 : result;
}
};
59.螺旋矩阵
边界条件太容易出错了
是一道训练边界条件很好的题目,要多练习
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int startx = 0;
int starty = 0;
int i,j;
int offset = 1;
int count = 1;
int loop = n/2;
vector<vector<int>> result(n, vector<int>(n,0));
while(loop--){
for(j = starty; j < n - offset; j++){
result[startx][j] = count++;
}
for(i = startx; i < n - offset; i++){
result[i][j] = count++;
}
for(; j > starty; j--){
result[i][j] = count++;
}
for(; i > startx; i--){
result[i][j] = count++;
}
startx++;
starty++;
offset++;
}
if(n % 2 == 1) result[n/2][n/2] = count;
return result;
}
};
前缀和
掌握前缀和 区间和知识
#include<iostream>
#include <vector>
using namespace std;
int main(){
int n, a, b;
cin >> n;
vector<int> vec(n);
vector<int> p(n);
int presum = 0;
for(int i = 0; i < n; i++){
cin >> vec[i];
presum += vec[i];
p[i] = presum;
}
while(cin >> a >> b){
int sum;
if(a == 0) sum = p[b];
else sum = p[b] - p[a - 1];
cout << sum << endl;
}
}