Skip to content

Commit 24d0cde

Browse files
authored
Update 1632-rank-transform-of-a-matrix.js
1 parent 6405532 commit 24d0cde

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

1632-rank-transform-of-a-matrix.js

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,91 @@
1+
class UF {
2+
constructor(n) {
3+
this.parent = new Array(n + 1).fill(0).map((_, i) => i);
4+
}
5+
union(x, y) {
6+
const rootX = this.find(x);
7+
const rootY = this.find(y);
8+
if (rootX !== rootY) {
9+
this.parent[rootX] = rootY;
10+
}
11+
}
12+
find(x) {
13+
if (x !== this.parent[x]) {
14+
this.parent[x] = this.find(this.parent[x]);
15+
}
16+
return this.parent[x];
17+
}
18+
}
19+
20+
// Update the matrixRankTransform function to use the union-find functions
21+
var matrixRankTransform = function(matrix) {
22+
const m = matrix.length
23+
const n = matrix[0].length
24+
const uf = new UF(m * n)
25+
const res = Array.from({ length: m }, () => Array(n).fill(-1))
26+
27+
for (let i = 0; i < m; i++) {
28+
const tmp = []
29+
for (let j = 0; j < n; j++) {
30+
tmp.push([matrix[i][j], i * n + j])
31+
}
32+
tmp.sort((a, b) => a[0] - b[0])
33+
for (let j = 1; j < n; j++) {
34+
if (tmp[j][0] === tmp[j - 1][0] && uf.find(tmp[j][1]) !== uf.find(tmp[j - 1][1])) {
35+
uf.union(tmp[j][1], tmp[j - 1][1])
36+
}
37+
}
38+
}
39+
40+
for (let j = 0; j < n; j++) {
41+
const tmp = []
42+
for (let i = 0; i < m; i++) {
43+
tmp.push([matrix[i][j], i * n + j])
44+
}
45+
tmp.sort((a, b) => a[0] - b[0])
46+
for (let i = 1; i < m; i++) {
47+
if (tmp[i][0] === tmp[i - 1][0] && uf.find(tmp[i][1]) !== uf.find(tmp[i - 1][1])) {
48+
uf.union(tmp[i][1], tmp[i - 1][1])
49+
}
50+
}
51+
}
52+
53+
const nums = [], group = {}
54+
for (let i = 0; i < m; i++) {
55+
for (let j = 0; j < n; j++) {
56+
const key = i * n + j
57+
const root = uf.find(key)
58+
if(group[root] == null) group[root] = []
59+
group[root].push(key)
60+
nums.push([matrix[i][j], key])
61+
}
62+
}
63+
nums.sort((a, b) => a[0] - b[0])
64+
const rowMax = Array(m).fill(0)
65+
const colMax = Array(n).fill(0)
66+
for(const e of nums) {
67+
const [val, key] = e
68+
const [i, j] = [Math.floor(key / n), key % n]
69+
if(res[i][j] !== -1) continue
70+
let rank = 0
71+
for(const k of group[uf.find(key)]) {
72+
const [x, y] = [Math.floor(k / n), k % n]
73+
rank = Math.max(rank, rowMax[x], colMax[y])
74+
}
75+
rank++
76+
for(const k of group[uf.find(key)]) {
77+
const [x, y] = [Math.floor(k / n), k % n]
78+
res[x][y] = rank
79+
rowMax[x] = rank
80+
colMax[y] = rank
81+
}
82+
}
83+
84+
return res
85+
};
86+
87+
// another
88+
189
/**
290
* @param {number[][]} matrix
391
* @return {number[][]}

0 commit comments

Comments
 (0)