1. 算法描述
Given a m * n matrix mat of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array.
给定 m * n 的整型矩阵mat, 按照左上到右下的顺序,升序排列对接线元素。
举例:
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
2. 思想分析
(1)遍历矩阵***第一行***元素,取出该对角线上的所有元素并且记录每个元素所对应的数组行列坐标[row, col];
(2)每一个元素row index + 1, col index + 1, 就可以得到下一个对角线上元素的[row, col];
(3)将[row, col]作为key, 对应的数值为value,存在一个map中;
(4)同时保存这些对应的数值,然后进行排序;
(5)遍历map, 取值,并且更新mat对应的[row, col]的元素;
(6)处理***第一列***剩余元素。
3. 参考代码
这里不讨论算法复杂度和代码风格,只是一份提交成功并且容易理解的参考代码
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
map<pair<int, int>, int> idxValMap;
const size_t row = mat.size();
const size_t col = mat[0].size();
// handle first row
for(int i = 0; i < col; i++)
{
int firstRow = 0;
int tmpCol = i;
vector<int> diagonalData;
idxValMap.clear();
while(firstRow < row || tmpCol < col)
{
pair<int, int> pairIdx = make_pair(firstRow, tmpCol);
idxValMap[pairIdx] = mat[firstRow][tmpCol];
diagonalData.push_back(mat[firstRow][tmpCol]);
firstRow++;
tmpCol++;
if(firstRow == row || tmpCol == col) break;
}
sort(diagonalData.begin(), diagonalData.end());
int start = 0;
for(auto & m : idxValMap)
{
m.second = diagonalData[start];
mat[m.first.first][m.first.second] = m.second;
start++;
}
}
// handle first col, excludes the first one in 1st column
for(int j = 1; j < row; j++)
{
int firstCol = 0;
int tmpRow = j;
vector<int> diagonalData;
idxValMap.clear();
while(firstCol < col || j < row)
{
pair<int, int> pairIdx = make_pair(tmpRow, firstCol);
idxValMap[pairIdx] = mat[tmpRow][firstCol];
diagonalData.push_back(mat[tmpRow][firstCol]);
firstCol++;
tmpRow++;
if(firstCol == col || tmpRow == row) break;
}
sort(diagonalData.begin(), diagonalData.end());
int start = 0;
for(auto & m : idxValMap)
{
m.second = diagonalData[start];
mat[m.first.first][m.first.second] = m.second;
start++;
}
}
return mat;
}
};