977. 有序数组的平方
双指针,新数组用k;
由于已经排序,所以比较两侧数据即可;
class Solution {
public:vector<int> sortedSquares(vector<int>& nums) {vector<int> ans(nums.size());int k = nums.size()-1;int left = 0;int right = nums.size()-1;while(left<=right){if(nums[left]*nums[left] > nums[right]*nums[right]){ans[k] = nums[left]*nums[left];left++;}else{ans[k] = nums[right]*nums[right];right--;}k--;}return ans;}
};
209. 长度最小的子数组
这道题需要注意的就是用while循环,使得sum减小到小于target,一次可能不够;
class Solution {
public:int minSubArrayLen(int target, vector<int>& nums) {int slowindex = 0;int fastindex = 0;int sum = 0;int minlen = INT_MAX;for(;fastindex<nums.size();++fastindex){sum += nums[fastindex];while(sum>=target){minlen = min(minlen, fastindex-slowindex+1);sum-=nums[slowindex];slowindex++;}}return minlen == INT_MAX? 0:minlen;}
};
59. 螺旋矩阵 II
设置四个边界,然后对边界不断缩小,注意边界换的变量要对之前不变的变量进行增减;比如t在第一个遍历中是不变量,第二个遍历中作为变量,就要在此之前++;
class Solution
{
public:vector<vector<int>> generateMatrix(int n){vector<vector<int>> mat(n, vector<int>(n)); int l = 0; int r = n-1; int t = 0;int b = n-1;int tar = n*n; int num = 1;while(num<=tar){for(int i=l;i<=r;++i) mat[t][i] = num++;t++;for(int i=t;i<=b;++i) mat[i][r] = num++;r--;for(int i=r;i>=l;--i) mat[b][i] = num++;b--;for(int i=b;i>=t;--i) mat[i][l] = num++;l++;}return mat;}
};