双指针
public:
vector<int> sortedSquares(vector<int>& nums) {
int n = nums.size();
vector<int> res(n);
for (int i = 0, j = n - 1, k = n - 1; i <= j;) {
if (nums[i] * nums[i] > nums[j] * nums[j]) {
res[k] = nums[i] * nums[i];
i ++, k -- ;
} else {
res[k] = nums[j] * nums[j];
j --, k -- ;
}
}
return res;
}
};
螺旋矩阵 II
提前定义方向
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector< vector<int>> res(n,vector<int>(n,0));
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
for(int x=0,y=0,i=0,d=0;i<n*n;i++){
res[x][y]=i+1;
int a=x+dx[d],b=y+dy[d];
if(a < 0 || a == n || b < 0 || b == n || res[a][b]){
d = (d+1 ) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
return res;
}
};