1. 有序数组的平方
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int left = 0;
int right = nums.size()-1;
int k = nums.size() - 1;
vector<int> result(nums.size(),0);
while (left <= right){
int left_num = nums[left] * nums[left];
int right_num = nums[right] * nums[right];
if (left_num < right_num){
result[k] = right_num;
right--;
}
else {
result[k] = left_num;
left++;
}
k--;
}
return result;
}
};
2. 长度最小的子数组
【重点】滑动窗口
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int slow = 0;
int quicksum = 0;
int len = 0;
int result = INT32_MAX;
for (int fast = 0; fast <= nums.size()-1; fast++){
quicksum += nums[fast];
while(quicksum >= target) {
len = fast - slow + 1;
result = result < len ? result : len;
quicksum -= nums[slow++];
}
}
return result == INT32_MAX ? 0 : result;
}
};
3. 螺旋矩阵II
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int startx = 0;
int starty = 0;
int loop = n/2;
int offset = 1;
int count = 1;
vector<vector<int>> result(n,vector<int>(n,0));
while (loop--) {
int i = startx;
int j = starty;
for (j; j < n-offset; j++) {
result[i][j] = count;
count++;
}
for (i; i < n-offset; i++) {
result[i][j] = count;
count++;
}
for (j;j > starty; j--) {
result[i][j] = count;
count++;
}
for (i;i > starty; i--) {
result[i][j] = count;
count++;
}
startx++;
starty++;
offset++;
}
if (n%2 != 0){
result[n/2][n/2] = count;
}
return result;
}
};