977. 有序数组的平方
LeetCode题目
注意事项
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int len = nums.size();
vector<int> num1(len, 0);
int left = 0;
int right = nums.size() - 1;
int pos = right;
while(left < right) {
int l2 = nums[left] * nums[left];
int r2 = nums[right] * nums[right];
if (l2 < r2) {
num1[pos--] = r2;
right--;
}
else if (l2 > r2) {
num1[pos--] = l2;
left++;
}
else {
num1[pos--] = l2;
left++;
num1[pos--] = r2;
right--;
}
}
if (left == right) num1[pos] = nums[left] * nums[left];
return num1;
}
};
209.长度最小的子数组
LeetCode题目
注意事项
- 判断好双指针控制的滑动窗的变化
- 判断好边界条件/特殊情况
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0;
int right = left;
int k = nums.size() + 1;
int sum = nums[0];
while(left <= right) {
if (sum < target) {
right++;
if (right == nums.size()) break;
sum += nums[right];
}
else {
if ((right - left + 1) < k) k = right - left + 1;
sum -= nums[left];
left++;
}
}
if (k == nums.size() + 1) k = 0;
return k;
}
};
59. 螺旋矩阵 II
LeetCode题目
注意事项
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> M(n, vector<int>(n, 0));
int l = -1, r = n, u = 0, d = n;
int x = 0, y = 0, num = n * n;
int ind = 1;
while(ind <= num) {
while(y < r)
M[x][y++] = ind++;
r--;
y--;
x++;
while(x < d)
M[x++][y] = ind++;
d--;
x--;
y--;
while(y > l)
M[x][y--] = ind++;
l++;
y++;
x--;
while(x > u)
M[x--][y] = ind++;
u++;
x++;
y++;
}
return M;
}
};