1329. Sort the Matrix Diagonally

问题:

对二维数组,对角线排序

Example 1:
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]]
 

Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100

 解法:

分别拿出对角线元素,组成数列,进行sort排序,再存入数组。

同一对角线上的元素mat[i][j],i-j是相同的。因此可以使用map的key来标记。value存同一对角线的元素。

方法1:c++的优先队列 priority_queue<int, vector<int>, greater<int>>

//默认是大顶堆 {5,4,3,2,1}
priority_queue<int> a; 
priority_queue<int, vector<int>, less<int> > a;

//小顶堆 {1,2,3,4,5}
priority_queue<int, vector<int>, greater<int> > c;

在使用 push(val)的时候,就已经开始一边插入一边排序了。

由于是队列,pop也将是从头到尾,由小到大弹出。

代码参考:

 1 class Solution {
 2 public:
 3     vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
 4         unordered_map<int, priority_queue<int, vector<int>, greater<int>>> d;
 5         int m=mat.size();
 6         int n=mat[0].size();
 7         for(int i=0; i<m; i++){
 8             for(int j=0; j<n; j++){
 9                 d[i-j].push(mat[i][j]);
10             }
11         }
12         for(int i=0; i<m; i++){
13             for(int j=0; j<n; j++){
14                 mat[i][j]=d[i-j].top();
15                 d[i-j].pop();
16             }
17         }
18         return mat;
19     }
20 };

方法2:直接使用vector,push_back依次存入元素后,

使用sort排序,再使用pop_back从后往前弹出元素,由大到小。

代码参考:

 1 class Solution {
 2 public:
 3     vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
 4         unordered_map<int, vector<int>> d;
 5         unordered_map<int, vector<int>>::iterator it;
 6         int m=mat.size();
 7         int n=mat[0].size();
 8         for(int i=0; i<m; i++){
 9             for(int j=0; j<n; j++){
10                 d[i-j].push_back(mat[i][j]);
11             }
12         }
13         for(it=d.begin(); it!=d.end(); it++){
14             sort(it->second.begin(),it->second.end());
15         }
16         for(int i=m-1; i>=0; i--){
17             for(int j=n-1; j>=0; j--){
18                 mat[i][j]=d[i-j].back();
19                 d[i-j].pop_back();
20             }
21         }
22         return mat;
23     }
24 };
原文地址:https://www.cnblogs.com/habibah-chang/p/13198146.html