明天开组会,今天忙着赶组会报告,先摆烂一天。
977.有序数组的平方:
个人想法:
利用双指针从两头开始,向中间行进。判断左右元素绝对值大小,对于大的计算后插入到res中。最后反转整个res就能得到答案。
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
vector<int> res;
int left = 0;
int right = nums.size()-1;
while(left<=right){
if(nums[left] + nums[right] >= 0){
res.push_back(nums[right]*nums[right]);
--right;
}
else{
res.push_back(nums[left]*nums[left]);
++left;
}
}
reverse(res.begin(),res.end());
return res;
}
};
209.长度最小的子数组:
滑动窗口解决
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int minlens = INT_MAX;
bool IsTrue = false;
int sum = 0;
int left = 0;
for(int i = 0;i < nums.size();i++){
sum += nums[i];
if(sum < target){
continue;
}
else{
while(sum >= target){
minlens = min(minlens,i - left + 1);
sum-=nums[left];
left++;
}
IsTrue = true;
}
}
if(IsTrue){
return minlens;
}
return 0;
}
};
59.螺旋矩阵II:
要注意模拟的时候,是前闭后开区间。一开始做的时候没注意,判断条件写了一堆
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int num = 1;
int left = 0, top = 0, right = n - 1, bottom = n - 1;
//初始化数组
vector<vector<int>> res(n,vector<int>(n));
while (num <= n*n ) {
//left to right
for (int i = left; i <= right; ++i) res[top][i] = num++;
++top;
//top to bottom
for (int i = top; i <= bottom; ++i) res[i][right] = num++;
--right;
//right to left
for (int i = right; i >= left; --i) res[bottom][i] = num++;
--bottom;
//bottom to top
for (int i = bottom; i >= top; --i) res[i][left] = num++;
++left;
}
return res;
}
};