File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-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
+ const maximizeXor = function ( nums , queries ) {
7
+ nums . sort ( ( a , b ) => a - b )
8
+ const numOfBits = 1 + Math . floor ( Math . log2 ( nums [ nums . length - 1 ] ) )
9
+ const maxMask = ( 1 << numOfBits ) - 1
10
+ return queries . map ( ( [ x , m ] ) => query ( x , m ) )
11
+ function query ( x , m ) {
12
+ if ( m < nums [ 0 ] ) return - 1
13
+ let l = 0 ,
14
+ r = nums . length
15
+ while ( l < r ) {
16
+ let mid = l + ( ( r - l ) >> 1 )
17
+ if ( m < nums [ mid ] ) r = mid
18
+ else l = mid + 1
19
+ }
20
+ r -= 1
21
+ l = 0
22
+ let ans = x & ~ maxMask
23
+ for ( let bit = numOfBits - 1 ; bit >= 0 ; bit -= 1 ) {
24
+ const mask = 1 << bit
25
+ if ( x & mask ) {
26
+ if ( ( nums [ l ] & mask ) === 0 ) {
27
+ ans |= 1 << bit
28
+ r = search ( l , r , mask ) - 1
29
+ }
30
+ } else {
31
+ if ( nums [ r ] & mask ) {
32
+ ans |= 1 << bit
33
+ l = search ( l , r , mask )
34
+ }
35
+ }
36
+ }
37
+ return ans
38
+ }
39
+ function search ( l , r , mask ) {
40
+ while ( l <= r ) {
41
+ const m = l + ( ( r - l ) >> 1 )
42
+ if ( ( nums [ m ] & mask ) === 0 ) l = m + 1
43
+ else r = m - 1
44
+ }
45
+ return l
46
+ }
47
+ }
48
+
49
+ // another
50
+
1
51
/**
2
52
* @param {number[] } nums
3
53
* @param {number[][] } queries
You can’t perform that action at this time.
0 commit comments