class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) { //双指针
int left = 0, right = nums.size() - 1;
int index = nums.size() - 1;
vector<int> res(nums.size(), 0);
while(left <= right){ //注意“=”条件
if(nums[left]*nums[left] <= nums[right]*nums[right]){
res[index] = nums[right]*nums[right];
index--; right--;
}
else {
res[index] = nums[left]*nums[left];
index--; left++;
}
}
return res;
}
};
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0;
int sum = 0, len = INT32_MAX;
for(int right = 0; right < nums.size(); right++){
sum += nums[right];
while(sum >= target){
len = min(len, right - left + 1); //基于符合条件的窗口更新窗口大小
sum -= nums[left];
left++; //左窗口滑动
}
}
return len == INT32_MAX ? 0 : len;
}
};
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0)); // 注意初始化
int cnt = 1;
int startx = 0, starty = 0; // 索引
for (int loop = 0; loop < n / 2; loop++) { // 转圈的次数
startx = loop; // 每次转圈的起始x索引
starty = loop; // 每次转圈的起始y索引
// 左闭右开不变原则
for (; starty < n - loop - 1; starty++) { //注意条件 n - loop - 1
res[startx][starty] = cnt;
cnt++;
}
for (; startx < n - loop - 1; startx++) { // 左闭右开不变原则
res[startx][starty] = cnt;
cnt++;
}
for (; starty > loop; starty--) { // 左闭右开不变原则
res[startx][starty] = cnt;
cnt++;
}
for (; startx > loop; startx--) { // 左闭右开不变原则
res[startx][starty] = cnt;
cnt++;
}
}
if (n % 2 == 1)
res[n / 2][n / 2] = n * n;
return res;
}
};