Google – Rearrange Matrix
input一个2D matrix, 重新排列里面的数字,使得它变成一个row wise and col wise sorted matrix. 意思就是每行递增,每列递增,每行不能出现相同的数字。
[Solution]
目前只能想到heap的解法,把所以数字加入minHeap,然后按列重新生成matrix。但感觉肯定有更快的方法。
Read full article from Google – Rearrange Matrix
input一个2D matrix, 重新排列里面的数字,使得它变成一个row wise and col wise sorted matrix. 意思就是每行递增,每列递增,每行不能出现相同的数字。
[Solution]
目前只能想到heap的解法,把所以数字加入minHeap,然后按列重新生成matrix。但感觉肯定有更快的方法。
public void rearrange(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return; } int m = matrix.length; int n = matrix[0].length; PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { minHeap.offer(matrix[i][j]); } } for (int j = 0; j < n; j++) { for (int i = 0; i < m; i++) { matrix[i][j] = minHeap.poll(); } } }