-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMaximum XOR With an Element From Array.java
90 lines (78 loc) · 2.42 KB
/
Maximum XOR With an Element From Array.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class Solution {
class QueryComparator implements Comparator<int[]> {
public int compare(int[] a, int[] b) {
return Integer.compare(a[1], b[1]);
}
}
class Node {
Node zero;
Node one;
public Node() {
this.zero = null;
this.one = null;
}
}
public int[] maximizeXor(int[] nums, int[][] queries) {
Arrays.sort(nums);
int len = queries.length;
int[][] queryWithIndex = new int[len][3];
for(int i = 0; i < len; i++) {
queryWithIndex[i][0] = queries[i][0];
queryWithIndex[i][1] = queries[i][1];
queryWithIndex[i][2] = i;
}
Arrays.sort(queryWithIndex, new QueryComparator());
int numId = 0;
int[] ans = new int[len];
Node root = new Node();
for(int i = 0; i < len; i++) {
while(numId < nums.length && nums[numId] <= queryWithIndex[i][1]) {
addNumToTree(nums[numId], root);
numId++;
}
ans[queryWithIndex[i][2]] = maxXOR(queryWithIndex[i][0], root);
}
return ans;
}
private void addNumToTree(int num, Node node) {
for(int i = 31; i >= 0; i--) {
int digit = (num >> i) & 1;
if (digit == 1) {
if (node.one == null) {
node.one = new Node();
}
node = node.one;
} else {
if (node.zero == null) {
node.zero = new Node();
}
node = node.zero;
}
}
}
private int maxXOR(int num, Node node) {
if (node.one == null && node.zero == null) {
return -1;
}
int ans = 0;
for(int i = 31; i >= 0 && node != null; i--) {
int digit = (num >> i) & 1;
if (digit == 1) {
if (node.zero != null) {
ans += (1 << i);
node = node.zero;
} else {
node = node.one;
}
} else {
if (node.one != null) {
ans += (1 << i);
node = node.one;
} else {
node = node.zero;
}
}
}
return ans;
}
}