2020/3/16,今天的每日一题是Leetcode59. 螺旋矩阵 II,题意如下:
这道题和昨天的那个很像,思路也差不多。没看过的点这里《[每日一题]Leetcode54. 螺旋矩阵》。只需要自己定义一个二维数组然后按照之前的题的方向变换。数组初始值全为0,有值的说明被填过了。然后改变方向就可以了。
c++代码如下:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int f[4][2]={{0,1}, {1,0},{0,-1},{-1,0}};//定义方向
int x=0,y=0;
int now=0;
vector<vector<int>> ans(n,vector<int>(n,0));
for(int i=0;i<n*n;i++)
{
ans[x][y]=i+1;
int nowx=x+f[now][0],nowy=y+f[now][1];
if(nowx>=n||nowx<0||nowy>=n||nowy<0||ans[nowx][nowy])
{
now=(now+1)%4;
}
x+=f[now][0];
y+=f[now][1];
}
return ans;
}
};
时间复杂度:O(N^2)。
(最近为了面试在看c++,所以算法题可能有点划了,c++看差不多再专注算法!)