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;
}
};