//977.有序数组的平方
//因为是有序的,因此平方和的最大值必然出现在两端,使用双指针法
class Solution {
public:
vector<int> sortedSquares(vector<int> &A) {
int n = A.size();
vector<int> res(n, 0); // 默认就是初始为0,也可以直接为 vector<int> res(n);
int head = 0, end = n - 1, tmp = n - 1;
while (head <= end) {
if (A[head] * A[head] >= A[end] * A[end]) {
res[tmp] = A[head];
tmp--;
head++;
} else {
res[tmp] = A[end];
tmp--;
end--;
}
}
return res;
}
};
//209. 长度最小的子数组
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int res = INT32_MAX;
int sum = 0;
int i = 0;
int subLength = 0;
for (int j = 0; j < nums.size(); j++) {
sum += nums[j];
while (sum >= target) {
subLength = j - i + 1;
res = res < subLength ? res : subLength;
sum -= nums[i++];
}
}
return res == INT32_MAX ? 0 : res;
}
};
//59.旋转矩阵
//使用左闭右开的区间方式
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 offset = 1;
int count = 1;
int i, j;
while (loop--) {
i = startx;
j = starty;
for (j = starty; j < n - offset; j++) {
res[i][j] = count;
count++;
}
for (i = startx; i < n - offset; i++) {
res[i][j] = count;
count++;
}
for (; j > starty; j--) {
res[i][j] = count;
count++;
}
for (; i > startx; i--) {
res[i][j] = count;
count++;
}
startx++;
starty++;
offset++;
}
if (n % 2 == 1) {
res[mid][mid] = count;
}
return res;
}
};