Skip to content

Commit a153c44

Browse files
authored
Update 1632-rank-transform-of-a-matrix.js
1 parent 3272ad9 commit a153c44

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

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

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,60 @@
1+
/**
2+
* @param {number[][]} matrix
3+
* @return {number[][]}
4+
*/
5+
const matrixRankTransform = function (matrix) {
6+
function find(UF, x) {
7+
if (x !== UF.get(x)) UF.set(x, find(UF, UF.get(x)))
8+
return UF.get(x)
9+
}
10+
function union(UF, x, y) {
11+
if (!UF.has(x)) UF.set(x, x)
12+
if (!UF.has(y)) UF.set(y, y)
13+
UF.set(find(UF, x), find(UF, y))
14+
}
15+
const m = matrix.length
16+
const n = matrix[0].length
17+
const UFs = new Map()
18+
for (let i = 0; i < m; i++) {
19+
for (let j = 0; j < n; j++) {
20+
const v = matrix[i][j]
21+
if (!UFs.has(v)) UFs.set(v, new Map())
22+
union(UFs.get(v), i, ~j)
23+
}
24+
}
25+
const value2index = {}
26+
for (let i = 0; i < m; i++) {
27+
for (let j = 0; j < n; j++) {
28+
let v = matrix[i][j]
29+
if (!value2index.hasOwnProperty(v)) value2index[v] = new Map()
30+
const indexes = value2index[v]
31+
let f = find(UFs.get(v), i)
32+
if (!indexes.has(f)) indexes.set(f, [])
33+
indexes.get(f).push([i, j])
34+
}
35+
}
36+
const answer = Array.from({ length: m }, () => Array(n).fill(0))
37+
const rowMax = Array(m).fill(0), colMax = Array(n).fill(0)
38+
const keys = Object.keys(value2index)
39+
keys.sort((a, b) => a - b)
40+
for (let v of keys) {
41+
for (let points of value2index[v].values()) {
42+
let rank = 1
43+
for (let point of points) {
44+
rank = Math.max(rank, Math.max(rowMax[point[0]], colMax[point[1]]) + 1)
45+
}
46+
for (let point of points) {
47+
answer[point[0]][point[1]] = rank
48+
rowMax[point[0]] = Math.max(rowMax[point[0]], rank)
49+
colMax[point[1]] = Math.max(colMax[point[1]], rank)
50+
}
51+
}
52+
}
53+
return answer
54+
}
55+
56+
// another
57+
158
/**
259
* @param {number[][]} matrix
360
* @return {number[][]}

0 commit comments

Comments
 (0)