Skip to content

Commit 742d3b1

Browse files
authored
Update 1054-distant-barcodes.js
1 parent 2e4c985 commit 742d3b1

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

1054-distant-barcodes.js

+45
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,48 @@ const rearrangeBarcodes = function(barcodes) {
2020

2121
return barcodes;
2222
};
23+
24+
// another
25+
26+
/**
27+
* @param {number[]} barcodes
28+
* @return {number[]}
29+
*/
30+
const rearrangeBarcodes = function(barcodes) {
31+
const hash = {}, n = barcodes.length
32+
for(let e of barcodes) {
33+
if(hash[e] == null) hash[e] = 0
34+
hash[e]++
35+
}
36+
const res = Array(n)
37+
let max = 0, idx = -1
38+
for(let k in hash) {
39+
if(hash[k] > max) {
40+
max = hash[k]
41+
idx = +k
42+
}
43+
}
44+
let i = 0
45+
// max freq first
46+
while(max > 0) {
47+
res[i] = idx
48+
max--
49+
i += 2
50+
}
51+
// the rest
52+
const keys = Object.keys(hash).map(e => +e)
53+
for(let j = 0, len = keys.length; j < len; j++) {
54+
if(keys[j] !== idx) {
55+
const k = keys[j]
56+
let freq = hash[k]
57+
while(freq > 0) {
58+
if(i >= n) i = 1
59+
res[i] = k
60+
freq--
61+
i += 2
62+
}
63+
}
64+
}
65+
66+
return res
67+
};

0 commit comments

Comments
 (0)