• 欢迎光临~

# 【算法训练营day2】LeetCode977. 有序数组的平方 209. 长度最小的子数组 59. 螺旋矩阵II

## LeetCode977. 有序数组的平方

### 初次尝试

``````class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int numslen = nums.size(), i;
vector<int> ans(numslen);

for (i = 0; i < numslen; i++) {
if(nums[i] >= 0) break;
}

int left = i - 1, right = i, count = 0;
while (left > -1 || right < numslen) {
if (left > -1 && right < numslen) {
if (-nums[left] >= nums[right]) {
ans[count] = nums[right] * nums[right];
count++;
right++;
}
else {
ans[count] = nums[left] * nums[left];
count++;
left--;
}
}
else if (left == -1) {
ans[count] = nums[right] * nums[right];
count++;
right++;
}
else if (right == numslen) {
ans[count] = nums[left] * nums[left];
count++;
left--;
}
}

return ans;
}
};
``````

``````class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int numslen = nums.size(), i;
vector<int> ans(numslen);

for (i = 0; i < numslen; i++) {
if(nums[i] >= 0) break;
}

int left = i - 1, right = i, count = 0;
while (left > -1 || right < numslen) {
if (left == -1 || -nums[left] >= nums[right]) {
ans[count] = nums[right] * nums[right];
count++;
right++;
}
else if (right == numslen || -nums[left] < nums[right]) {
ans[count] = nums[left] * nums[left];
count++;
left--;
}
}

return ans;
}
};
``````

### 看完代码随想录后的想法

``````class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int numslen = nums.size();
vector<int> ans(numslen);

int left = 0, right = numslen - 1;
while (left <= right) {
if (nums[left] * nums[left] < nums[right] * nums[right]) {
ans[numslen-1] = nums[right] * nums[right];
numslen--;
right--;
}
else {
ans[numslen-1] = nums[left] * nums[left];
numslen--;
left++;
}
}

return ans;
}
};
``````

## LeetCode209. 长度最小的子数组

### 初次尝试

``````class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int numsSize = nums.size();
int left = 0, right = 0, sum = 0, ans = INT_MAX;

while (right < numsSize) {
sum += nums[right];
if (sum >= target) {
ans = min(ans, right - left + 1);
left++;
right = left;
sum = 0;
}
else right++;
}

return ans == INT_MAX? 0 : ans;
}
};
``````

### 看完代码随想录后的想法

``````class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int numsSize = nums.size();
int left = 0, right = 0, sum = 0, ans = INT_MAX;

for (; right < numsSize; right++) {
sum += nums[right];
while (sum >= target) {
ans = min(ans, right - left + 1);
sum -= nums[left++];
}
}

return ans == INT_MAX ? 0 : ans;
}
};
``````

## LeetCode59. 螺旋矩阵II

### 初次尝试

``````class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, 0));
int row = 0, col = 0;

for (int num = 1; num <= n * n; num++) {
ans[row][col] = num;
if (row <= col && col < n - 1 - row) {
col++;
}
else if (row < col && col >= n - 1 - row) {
row++;
}
else if (row >= col && col > n - 1 - row) {
col--;
}
else if (row > col && col <= n - 1 - row) {
if (row == col + 1) {
col++;
}
else {
row--;
}
}
}

return ans;
}
};
``````