977. 有序数组的平方
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
for (int i = 0; i < nums.size(); i++) {
nums[i] = nums[i] *nums[i];
}
sort(nums.begin(), nums.end());
return nums;
}
};
```cpp
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int k = nums.size() - 1;
vector<int> result(nums.size(), 0);
for(int i = 0, j = nums.size() - 1; i <= j;) {
if (nums[i] * nums[i] > nums[j] * nums[j]) {
result[k] = nums[i] * nums[i];
k--;
i++;
} else {
result[k] = nums[j] * nums[j];
k--;
j--;
}
}
return result;
}
};
209. 长度最小的子数组
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int result = INT32_MAX;
int subLength = 0;
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum = 0;
for (int j = i; j < nums.size(); j++) {
sum += nums[j];
while (sum >= target) {
subLength = j - i + 1;
result = result < subLength ? result :subLength;
break;
}
}
}
return result == INT32_MAX ? 0: result;
}
};
// 滑动窗口
// O(n)
// 滑动窗口:意思也就是双指针的变式,关键是确定好窗口的终止位置和起始位置。**就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果。**
// 定义j确定为终止位置,当sum>target时,此时就是找到的子序列,开始移动i起始位置
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int result = INT32_MAX;
int i = 0; // 起始位置
int subLength = 0; // 滑动窗口长度即子序列长度
int sum = 0; // 滑动窗口数值的和
for (int j = 0; j < nums.size(); j++) {
sum += nums[j];
while (sum >= target) {
subLength = j - i + 1;
result = result < subLength ? result : subLength;
sum -= nums[i]; // 滑动窗口最重要的的点,当找到子序列时,固定终止位置j,开始移动起始位置i进行判断
i++;
}
}
return result == INT32_MAX ? 0 : result;
}
};
54. 螺旋矩阵
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int startx = 0,starty = 0;
int loop = n / 2;
int mid = n / 2;
int count = 1;
int offset = 1;
int i, j;
while (loop--) {
i = startx;
j = starty;
for (j = starty; j < n - offset; j++) {
res[startx][j] = count++;
}
for (i = startx; i < n - offset; i++) {
res[i][j] = count++;
}
for (;j > starty; j--) {
res[i][j] = count++;
}
for (;i > startx; i--) {
res[i][j] = count++;
}
startx++;
starty++;
offset += 1;
}
if (n % 2 == 1) {
res[mid][mid] = count;
}
return res;
}
};