有序数组的平方
两边的边界是不好处理的情况,从大到小!
// 双指针 从大到小!!
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int n = nums.size();
vector<int> res(n);
if (n == 1) return {nums[0] * nums[0]};
int i = 0, j = n - 1, idx = n - 1;
while (i <= j)
{
if (nums[i] * nums[i] <= nums[j] * nums[j])
{
res[idx--] = nums[j] * nums[j--];
}
else
res[idx--] = nums[i] * nums[i++];
}
return res;
}
};
长度最小的子数组
很典型的滑动窗口
// 滑动窗口
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int n = nums.size();
int sum = 0, minn = 1e9;
int i = 0, j = 0;
while (j < n && i <= j)
{
sum += nums[j];
while (sum >= target)
{
minn = min(minn, j - i + 1);
sum -= nums[i];
i ++;
}
j ++;
}
return minn == 1e9 ? 0 : minn;
}
};
螺旋矩阵 II
就是蛇形矩阵
class Solution {
public:
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res;
res.resize(n);
for (auto &i : res) i.resize(n);
int x = 0, y = 0, f = 0, num = 2;
res[0][0] = 1;
for (int t = 1; t < n * n; t ++)
{
int xx = x + dx[f];
int yy = y + dy[f];
if (xx >= n || xx < 0 || yy >= n || yy < 0 || res[xx][yy])
{
f = (f + 1) % 4;
xx = x + dx[f];
yy = y + dy[f];
}
// cout << xx << ' ' << yy << endl;
res[xx][yy] = num ++;
x = xx, y = yy;
}
return res;
}
};