分析
我们只需要将对角线上的元素放置到vector中进行排序,排序完成在依次放回便可完成此问题。
不过这里有一个对角线元素性质,可以让代码更为优美。
即如果a(x1, y1)
和 b(x2, y2)
位于同一个对角线上,那么x1 - y1 == x2 - y2
。
代码
class Solution {
public:
void sortOneDia(vector<vector<int>>& mat, int x, int y){
vector<int> ascorder;
int xx{x}, yy{y}, i;
while(xx < mat.size() && yy < mat[xx].size()){
ascorder.push_back(mat[xx][yy]);
xx++, yy++;
}
sort(ascorder.begin(), ascorder.end());
xx = x, yy = y, i = 0;
while(xx < mat.size() && yy < mat[xx].size()){
mat[xx][yy] = ascorder[i];
xx++, yy++, i++;
}
return;
}
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
for(int x = 0; x < mat.size(); x++)
sortOneDia(mat, x, 0);
for(int y = 1; y < mat[0].size(); y++)
sortOneDia(mat, 0, y);
return mat;
}
};