1. 程式人生 > 實用技巧 >1329. Sort the Matrix Diagonally

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