day2
977.有序数组的平方
找到最小值点即可,类似归并排序的收尾部分。
双指针有点意思,思路不一样,从两边到中间。
209.长度最小的子数组
不会,自己想不出来。看了一点提示之后,自己写还是容易写成屎山:
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0, right = 0;
int sum = nums[0];
while (right < nums.size() && sum < target) {
right++;
if (right == nums.size()) return 0;
sum += nums[right];
}
int length = right - left + 1;
while (right < nums.size()) {
// cout << left <<"-"<< right <<":"<<length<<endl;
if(sum >= target) {
sum -= nums[left];
left++;
if (sum >= target && right - left + 1 < length) {
length = right - left + 1;
}
}
else {
right++;
if (right < nums.size()) sum += nums[right];
else return length;
}
}
return length;
}
};
较为优雅的代码,双指针的移动逻辑也更为清晰:
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0, right = 0;
int sum = 0;
int length = INT_MAX;
while (right < nums.size()) {
sum += nums[right];
while (sum >= target) {
if(right - left + 1 < length) length = right - left + 1;
sum -= nums[left++];
}
right++;
}
if(length == INT_MAX) return 0;
else return length;
}
};
类似题目还没做
59.螺旋矩阵II
我甚至觉得我这个版本更简洁,但是中间也经历了不少debug:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int num = 1;
int loop = n / 2;
int depth = 0;
while (depth < loop) {
int x = depth, y = depth;
for(int i = 0; i < n - depth * 2 - 1; y++, i++) res[x][y] = num++;
for(int i = 0; i < n - depth * 2 - 1; x++, i++) res[x][y] = num++;
for(int i = 0; i < n - depth * 2 - 1; y--, i++) res[x][y] = num++;
for(int i = 0; i < n - depth * 2 - 1; x--, i++) res[x][y] = num++;
depth++;
}
if (n % 2 == 1) res[n/2][n/2] = num;
return res;
}
};
类似题目还没做