Leetcode 977.有序数组的平方
题目链接
977.有序数组的平方
题解
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int left = 0, right = nums.size() - 1, index = nums.size() - 1;
vector<int> res(nums.size());
//vector<int> res;
while (left <= right) {
int temp1 = nums[left] * nums[left];
int temp2 = nums[right] * nums[right];
if (temp1 < temp2) {
//res.push_back(temp2);
res[index --] = temp2;
right --;
}
else {
//res.push_back(temp1);
res[index --] = temp1;
left ++;
}
}
//reverse(res.begin(), res.end());
return res;
}
}
Leetcode 209.长度最小的子数组
题目链接
209. 长度最小的子数组
题解
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int start = 0, end = 0, sum =0, sub_length = nums.size() + 1;
while (end < nums.size()) {
//while (sum < target && end <nums.size()) {
sum += nums[end];
end++;
//}
while (sum >= target) {
sum -= nums[start];
start++;
if (end - start +1 < sub_length) {
sub_length = end - start +1;
}
}
}
if (sub_length == nums.size() + 1) return 0;
else return sub_length;
}
};
Leetcode 59.螺旋矩阵II
题目链接
59. 螺旋矩阵 II
题解
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int left = 0, right = n - 1, up = 0, down = n - 1, index = 1;
while (1) {
for (int i = left; i <= right; i ++) res[up][i] = index ++;
up ++;
if (up > down) return res;
for (int i = up; i <= down; i ++) res[i][right] = index ++;
right --;
if (left > right) return res;
for (int i = right; i >= left; i --) res[down][i] = index ++;
down --;
if (up > down) return res;
for (int i = down; i >= up; i --) res[i][left] = index ++;
left ++;
if (left > right) return res;
}
}
};