59螺旋函数2
这个和之前的螺旋函数是一样的,只是直接知道数组,让遍历,现在遍历好了让输入数组,完全可以用一模一样的解法
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n);
for(int i = 0; i < n; i++){
res[i].resize(n);
}
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
int count = 1;
while (left <= right && top <= bottom){
for(int i = left; i <= right; i ++){
res[top][i] = count ++;
}
for(int i = top + 1; i <= bottom; i++){
res[i][right] = count++;
}
if(left < right && top < bottom){
for(int i = right - 1; i >= left; i--){
res[bottom][i] = count++;
}
for(int i = bottom - 1; i > top; i --){
res[i][left] = count++;
}
}
left++;
right--;
top++;
bottom--;
}
return res;
}
};
时间复杂度O(N*N),空间复杂度O(1)
498对角线遍历
这个也是二维数组遍历问题,感觉也没有什么坑点和需要注意的算法,就是抓住规律去遍历他,可是可是可是!!!
为什么一直报错???自己怎么算都是对的为什么一直报错????
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
int row = 0;
int col = 0;
vector<int> res;
res.push_back(mat[row][col]);
while(row != m || col != n){
//右上
while(col ++ < n){
if(row -- >= 0) res.push_back(mat[row][col]); //右上
else{ //右
row = 0;//超出边界则取边界
res.push_back(mat[row][col]);
break;
}
}
// //左下
while(row ++ < m){
if(col -- >= 0) res.push_back(mat[row][col]);
else{
col = 0;//超出边界则取边界
res.push_back(mat[row][col]);
break;
}
}
}
return res;
}
};
一直是Line 1034: Char 34: runtime error: addition of unsigned offset to 0x603000000010 overflowed to 0x602ffffffff8 (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
查了一下大概是数组越界或者出现不确定的下标,可是为什么用最简单的例子也会这样???
已经改了两个小时还没看出问题的我崩溃了
明天写个完整函数gdb一下吧,太难了。
果然改bug不能死磕,昨天俩小时出不来,今天两分钟解决。太傻了,又犯简单问题,把 col++ < n 改成++ col < n;先加再比较,要把加写前面,以为比较就没有先后的区别
,改了之后遇到[[1,2]]例子会超时,因为没有判断好循环的退出条件
改成
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
int row = 0;
int col = 0;
vector<int> res;
res.push_back(mat[row][col]);
while(row <= m && col <= n){
//右上
while(++ col < n){
if(-- row >= 0) res.push_back(mat[row][col]); //右上
else{ //右
row = 0;//超出边界则取边界
res.push_back(mat[row][col]);
break;
}
}
//左下
while(++ row < m){
if(-- col >= 0) res.push_back(mat[row][col]);
else{
col = 0;//超出边界则取边界
res.push_back(mat[row][col]);
break;
}
}
}
return res;
}
};
就过了