Given a two-dimensional integer matrix, sort each of the columns in ascending order.
Example 1
Inputmatrix = [ [10, 20, 30], [5, 5, 3], [0, 10, 7] ]Output
[ [0, 5, 3], [5, 10, 7], [10, 20, 30] ]
Column Sort
In order to utilize the inbuilt/provided sorting library, we have to transpose the matrix so that the columns are continuous arrays. Then after sorting, we need to transpose the matrix back.
vector<vector<int>> solve(vector<vector<int>>& matrix) {
function<void(vector<vector<int>> &m)> transpose = [](vector<vector<int>> &m) {
vector<vector<int>> n(m[0].size(), vector<int>(m.size()));
for (int r = 0; r < m.size(); ++ r) {
for (int c = 0; c < m[0].size(); ++ c) {
n[c][r] = m[r][c];
}
}
m = n;
};
transpose(matrix);
for (int r = 0; r < matrix.size(); ++ r) {
sort(begin(matrix[r]), end(matrix[r]));
}
transpose(matrix);
return matrix;
}
Transposing the matrix takes O(NM) time and space. Then sorting takes O(MNLogN) where N is the number of rows and M is the number of columns.
–EOF (The Ultimate Computing & Technology Blog) —
257 wordsLast Post: C++ Implementation of Segment Tree
Next Post: From Breadth First Search Algorithm to Dijkstra Shortest Distance from Source to Every Vertex