Skip to content

Commit d74f875

Browse files
authored
Update 1707-maximum-xor-with-an-element-from-array.js
1 parent 8e06c7a commit d74f875

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

1707-maximum-xor-with-an-element-from-array.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,58 @@ const maximizeXor = function (nums, queries) {
9999
}
100100
return result
101101
}
102+
103+
// another
104+
// though not enough memory, this method still provides a method to solve this kind of problem
105+
106+
class Trie {
107+
constructor() {
108+
this.next = Array(2).fill(null)
109+
}
110+
}
111+
/**
112+
* @param {number[]} nums
113+
* @param {number[][]} queries
114+
* @return {number[]}
115+
*/
116+
const maximizeXor = function(nums, queries) {
117+
nums.sort((a, b) => a - b)
118+
queries.forEach((e, i) => e.push(i))
119+
queries.sort((a, b) => a[1] - b[1])
120+
const n = nums.length
121+
let idx = 0
122+
const res = []
123+
const root = new Trie()
124+
for(const [x, m, qi] of queries) {
125+
126+
while(idx < n && nums[idx] <= m) {
127+
let cur = root, val = nums[idx]
128+
for(let i = 29; i >= 0; i--) {
129+
const tmp = (val >> i) & 1
130+
if(cur.next[tmp] == null) cur.next[tmp] = new Trie()
131+
cur = cur.next[tmp]
132+
}
133+
idx++
134+
}
135+
if(idx === 0) {
136+
res[qi] = -1
137+
continue
138+
}
139+
140+
let tmp = 0, cur = root
141+
for(let i = 29; i >= 0; i--) {
142+
const val = 1 - ((x >> i) & 1)
143+
if(cur.next[val] != null) {
144+
tmp = tmp * 2 + 1
145+
cur = cur.next[val]
146+
} else {
147+
tmp = tmp * 2
148+
cur = cur.next[1 - val]
149+
}
150+
151+
}
152+
153+
res[qi] = tmp
154+
}
155+
return res
156+
};

0 commit comments

Comments
 (0)