4
public int[][] matrixRankTransform(int[][] matrix) {6
int n = matrix[0].length;7
int[][] answer = new int[m][n];9
// GROUP BY MATRIX VAL -> {X,Y}10
TreeMap<Integer, List<int[]>> map = new TreeMap<>();11
for (int i = 0; i < m; i++) {12
for (int j = 0; j < n; j++) {14
int val = matrix[i][j];15
if (map.get(val) == null) map.put(val, new ArrayList<>());20
// INITIALIZE MIN-RANK ARRAY FOR EVERY COL/ROW21
int[] minX = new int[m];22
int[] minY = new int[n];24
for (Integer key : map.keySet()) {25
List<int[]> list = map.get(key);27
// SPLIT TO GROUPS USING UNION FIND FOR VALs IN SAME COL/ROW28
int lSize = list.size();29
parent = new int[lSize];30
for (int i = 0; i < lSize; i++) parent[i] = i;32
// Group the xy by col and row then union by row & by col33
HashMap<Integer, List<Integer>> xMap = new HashMap<>();34
HashMap<Integer, List<Integer>> yMap = new HashMap<>();35
for (int i = 0; i < lSize; i++) {36
int[] xy = list.get(i);40
if (xMap.get(x) == null) xMap.put(x, new ArrayList<>());41
if (yMap.get(y) == null) yMap.put(y, new ArrayList<>());47
for (Integer xKey : xMap.keySet()) {48
List<Integer> xList = xMap.get(xKey);49
for (int i = 1; i < xList.size(); i++) {50
union(xList.get(i - 1), xList.get(i));55
for (Integer yKey : yMap.keySet()) {56
List<Integer> yList = yMap.get(yKey);57
for (int i = 1; i < yList.size(); i++) {58
union(yList.get(i - 1), yList.get(i));62
HashMap<Integer, List<int[]>> group = new HashMap<>();63
for (int i = 0; i < lSize; i++) {65
if (group.get(grp) == null) group.put(grp, new ArrayList<>());66
group.get(grp).add(list.get(i));69
// SET ANSWER FOR EACH GROUP70
for (Integer grpKey : group.keySet()) {72
List<int[]> sublist = group.get(grpKey);74
// FIND MAX-RANK FOR THIS GROUP75
for (int[] xy : sublist) {79
max = Math.max(max, Math.max(minX[x], minY[y]));82
// UPDATE ANSWER = MAX-RANK AND SET NEW MIN-RANK FOR ROW/COL = MAX-RANK+183
for (int[] xy : sublist) {96
void union(int a, int b) {105
parent[a] = find(pa);