Skip to content

Commit 99fdc7b

Browse files
authored
Update 1649-create-sorted-array-through-instructions.js
1 parent 5346a23 commit 99fdc7b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

1649-create-sorted-array-through-instructions.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,50 @@ const createSortedArray = function(instructions) {
3434
}
3535
return res
3636
};
37+
38+
// another
39+
40+
/**
41+
* @param {number[]} instructions
42+
* @return {number}
43+
*/
44+
const createSortedArray = function (instructions) {
45+
const ins = instructions, n = ins.length
46+
let res = 0
47+
const mod = 1e9 + 7, { min } = Math
48+
const bit = new BIT(1e5)
49+
for(let i = 0; i < n; i++) {
50+
const cur = ins[i]
51+
res = (res + min(bit.query(cur - 1), i - bit.query(cur))) % mod
52+
bit.update(cur, 1)
53+
}
54+
55+
return res
56+
}
57+
58+
function lowBit(x) {
59+
return x & -x
60+
}
61+
class BIT {
62+
constructor(n) {
63+
this.arr = Array(n + 1).fill(0)
64+
}
65+
66+
update(i, delta) {
67+
if(i < 1) return
68+
while (i < this.arr.length) {
69+
this.arr[i] += delta
70+
i += lowBit(i)
71+
}
72+
}
73+
74+
query(i) {
75+
let res = 0
76+
if(i < 1) return res
77+
while (i > 0) {
78+
res += this.arr[i]
79+
i -= lowBit(i)
80+
}
81+
return res
82+
}
83+
}

0 commit comments

Comments
 (0)