class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int size = nums.size();
vector<int> result;
for (int i = 0; i < size; i++) {
result.push_back(nums[i] * nums[i]);
}
sort(result.begin(), result.end());
return result;
}
};
注意点:
- vector新增一个元素是push_back()
2.vector.begin()、vector.end()
3.sort()函数的用法
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int subLength = 0;
int sum = 0;
int result = INT_MAX;
int j = 0;
int i = j;
while (j < nums.size()) {
sum += nums[j];
while (sum >=target) {
subLength = (j-i) + 1;
result = subLength < result ? subLength:result;
sum -= nums[i];
i++;
}
j++;
}
return result < INT_MAX?result:0;
}
};
注意点:
- 双指针
2.滑动窗口
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int up = 0, down = n - 1, left = 0, right = n - 1;
int index = 1;
vector<vector<int>> result(n, vector<int>(n));
while (index <= n * n) {
for (int i = left; i <= right ; i++) {
result[up][i] = index;
index++;
}
up++;
for(int i = up; i <=down;i++){
result[i][right] = index;
index++;
}
right--;
for(int i = right;i>=left;i--){
result[down][i] = index;
index++;
}
down--;
for(int i= down;i>=up;i--) {
result[i][left] = index;
index++;
}
left++;
}
return result;
}
};
注意点:
- vector<int> (n) 初始化一个数量为n、值为0的数组;
2.二维数组初始化方式 vector<vector<int>> result(n, vector<int>(n))
就直接模拟就可以了。注意边界上下左右的初始值、循环的边界值、还有循环内部边界值怎么变就可以。