File tree 1 file changed +62
-0
lines changed
1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums
3
+ * @param {number[][] } queries
4
+ * @return {number[] }
5
+ */
6
+ var maximizeXor = function ( nums , queries ) {
7
+ nums . sort ( ( a , b ) => a - b )
8
+ const n = nums . length
9
+ queries . forEach ( ( query , index ) => {
10
+ query . push ( index )
11
+ } )
12
+ queries . sort ( ( a , b ) => a [ 1 ] - b [ 1 ] )
13
+ const trie = new Trie ( )
14
+ let i = 0
15
+ const res = [ ]
16
+ queries . forEach ( ( [ x , m , index ] ) => {
17
+ while ( i < n && nums [ i ] <= m ) {
18
+ trie . insert ( nums [ i ] )
19
+ i ++
20
+ }
21
+
22
+ res [ index ] = trie . query ( x )
23
+
24
+ } )
25
+ return res
26
+ } ;
27
+
28
+ class Trie {
29
+ constructor ( ) {
30
+ this . root = { }
31
+ }
32
+ insert ( num ) {
33
+ let node = this . root
34
+ for ( let i = 31 ; i >= 0 ; i -- ) {
35
+ const bit = ( num >> i ) & 1
36
+ if ( ! node [ bit ] ) {
37
+ node [ bit ] = { }
38
+ }
39
+ node = node [ bit ]
40
+ }
41
+ }
42
+ query ( num ) {
43
+ let node = this . root
44
+ if ( Object . keys ( node ) . length === 0 ) return - 1
45
+ let res = 0
46
+ for ( let i = 31 ; i >= 0 ; i -- ) {
47
+ const bit = ( num >> i ) & 1
48
+ if ( node == null ) break
49
+ if ( node [ 1 - bit ] ) {
50
+ res |= 1 << i
51
+ node = node [ 1 - bit ]
52
+ } else {
53
+ node = node [ bit ]
54
+ }
55
+ }
56
+ return res
57
+ }
58
+ }
59
+
60
+ // another
61
+
62
+
1
63
/**
2
64
* @param {number[] } nums
3
65
* @param {number[][] } queries
You can’t perform that action at this time.
0 commit comments