File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -34,3 +34,50 @@ const createSortedArray = function(instructions) {
34
34
}
35
35
return res
36
36
} ;
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
+ }
You can’t perform that action at this time.
0 commit comments