第一题是长度最小的子数组,初次接触滑动窗口,先调节窗口末端即符合要求的子数组的最后一位,再依次缩小窗口初始位置从而找到最小满足题意的子数组。
class Solution {
public:int minSubArrayLen(int target, vector<int>& nums) {int result = INT32_MAX;int sum = 0;int i = 0;int lenght = 0;for (int j = 0; j < nums.size(); j++) {sum += nums[j];while (sum >= target) {lenght = (j - i + 1);sum -= nums[i];i++;if (result > lenght) {result = lenght;}}}if (result == INT32_MAX)return 0;return result;}
};
第二题是螺旋矩阵II。掌握每次处理的不变原则,如左闭右开或左开右闭,在每次处理是对个对角元素应采取相同的处理方式。
class Solution {
public:vector<vector<int>> generateMatrix(int n) {vector<vector<int>> res(n, vector<int>(n, 0));int startx = 0, starty = 0;int offset = 1;int count = 1;int loop = n / 2;while (loop--) {int i, j;for (j = starty; j < (n - offset); j++)res[startx][j] = count++;for (i = startx; i < (n - offset); i++)res[i][j] = count++;for (; j > starty; j--)res[i][j] = count++;for (; i > startx; i--)res[i][j] = count++;startx++;starty++;offset++;}if (n % 2 == 1) {res[n / 2][n / 2] = n * n;}return res;}
};
第三题是螺旋矩阵,思路与上题相同,跳出循环时需要单独处理三种情况:1.边长为奇数的正方形矩阵;2.列数为奇数的最中间一列;3.行数为奇数的最中间一行,以上情况用if else处理,其余便利过程与上一题相同。
class Solution {
public:vector<int> spiralOrder(vector<vector<int>>& matrix) {int rows = matrix.size();int cloumns = matrix[0].size();int loops = min(rows, cloumns) / 2;int startx = 0;int starty = 0;int offset = 1;int num = 0;vector<int> res(rows * cloumns);while (loops--) {int i, j;for (j = starty; j < (cloumns - offset); j++)res[num++] = matrix[startx][j];for (i = startx; i < (rows - offset); i++)res[num++] = matrix[i][j];for (; j > starty; j--)res[num++] = matrix[i][j];for (; i > startx; i--)res[num++] = matrix[i][j];startx++;starty++;offset++;}if(cloumns==rows&&rows%2==1)res[num]=matrix[rows/2][cloumns/2];else if(rows%2==1&&startx==rows/2){for(int j = starty;j<=cloumns-offset;j++)res[num++]=matrix[startx][j];}else if(cloumns%2==1&&starty==cloumns/2){for(int i = startx;i<=rows-offset;i++)res[num++]=matrix[i][starty];}return res;}
};
第四题是区间和。从该题学到前缀和,用新数组p表示原数组的第一个加到对应位置的总和,主要注意一下程序的输入输出。
#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++){scanf("%d",&vec[i]);presum += vec[i];p[i] = presum;}while (scanf("%d%d", &a, &b)==2) {int sum;if (a == 0) sum = p[b];else sum = p[b] - p[a - 1];printf("%d\n", sum);}
}