File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -44,3 +44,51 @@ class Trie {
44
44
return ans
45
45
}
46
46
}
47
+
48
+
49
+ // another
50
+
51
+ /**
52
+ * @param {number[] } nums
53
+ * @param {number } low
54
+ * @param {number } high
55
+ * @return {number }
56
+ */
57
+ const countPairs = function ( nums , low , high ) {
58
+ let res = 0 , n = nums . length , trie = { cnt : 0 }
59
+ for ( const e of nums ) {
60
+ res += helper ( e , high + 1 ) - helper ( e , low )
61
+ insert ( e )
62
+ }
63
+ return res
64
+
65
+ function helper ( e , limit ) {
66
+ let res = 0 , cur = trie
67
+ for ( let i = 14 ; i >= 0 ; i -- ) {
68
+ const a = ( e >> i ) & 1
69
+ const b = ( limit >> i ) & 1
70
+ if ( cur == null ) break
71
+ if ( b === 0 ) {
72
+ cur = cur [ a ]
73
+ continue
74
+ }
75
+ if ( cur [ a ] ) {
76
+ res += cur [ a ] . cnt
77
+ }
78
+ cur = cur [ 1 - a ]
79
+ }
80
+
81
+ return res
82
+ }
83
+
84
+ function insert ( e ) {
85
+ let cur = trie
86
+ for ( let i = 14 ; i >= 0 ; i -- ) {
87
+ const tmp = ( e >> i ) & 1
88
+ if ( ! ( tmp in cur ) ) cur [ tmp ] = { cnt :0 }
89
+ cur [ tmp ] . cnt ++
90
+ cur = cur [ tmp ]
91
+ }
92
+ }
93
+
94
+ } ;
You can’t perform that action at this time.
0 commit comments