题目
代码(首刷看解析)
作图模拟一遍会理解更快。
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<int> res;
// 一共m+n-1条对角线
for(int i = 0; i < m+n-1; i++) {
if(i % 2 == 0) { // 从下往上
int x = i < m ? i : m - 1;
int y = i < m ? 0 : i - m + 1;
while(x >= 0 && y < n) {
res.emplace_back(mat[x--][y++]);
}
} else {
int x = i < n ? 0 : i - n + 1;
int y = i < n ?i : n - 1;
while(x < m && y >= 0) {
res.emplace_back(mat[x++][y--]);
}
}
}
return res;
}
};
代码(10.2 二刷看解析)
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<int> res;
for(int i = 0; i < m+n-1; i++) {
if(i%2==0) {
int x = i < m ? i : m-1;
int y = i < m ? 0 : i-m+1;
while(x >= 0 && y < n)
res.emplace_back(mat[x--][y++]);
} else {
int x = i < n ? 0 : i-n+1;
int y = i < n ? i : n-1;
while(x < m && y >= 0)
res.emplace_back(mat[x++][y--]);
}
}
return res;
}
};