1
+ // 很明显可以使用n2的时间复杂度以及常数的空间复杂度解决问题
2
+ // 但是可以用前缀树来以空间换取时间实现线性的时间复杂度
3
+ // https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/130427/()-92
4
+
5
+ // Runtime: 164 ms, faster than 23.69% of C++ online submissions for Maximum XOR of Two Numbers in an Array.
6
+ // Memory Usage: 108.1 MB, less than 10.00% of C++ online submissions for Maximum XOR of Two Numbers in an Array.
7
+
8
+ struct TrieNode
9
+ {
10
+ TrieNode* left = nullptr ;
11
+ TrieNode* right = nullptr ;
12
+ };
13
+
14
+ class Solution
15
+ {
16
+ public:
17
+ Solution () : root(new TrieNode()) {}
18
+
19
+ ~Solution () { clear (root); }
20
+
21
+ int findMaximumXOR (vector<int >& nums)
22
+ {
23
+ // 建立前缀树
24
+ buildTrie (nums);
25
+
26
+ // 迭代查找
27
+ int res = INT_MIN;
28
+ for (auto item : nums)
29
+ {
30
+ int temp = 0 ;
31
+ TrieNode* head = root;
32
+ for (int i = 1 , ptr = 0x40000000 ; i < 32 ; ++i, ptr >>= 1 )
33
+ {
34
+ int carry = 0 ;
35
+
36
+ if (ptr & item)
37
+ {
38
+ if (head->left == nullptr ) head = head->right ;
39
+ else ++carry, head = head->left ;
40
+ }
41
+ else
42
+ {
43
+ if (head->right == nullptr ) head = head->left ;
44
+ else ++carry, head = head->right ;
45
+ }
46
+
47
+ temp *= 2 ;
48
+ temp += carry;
49
+ }
50
+ res = temp > res ? temp : res;
51
+ }
52
+ return res;
53
+ }
54
+
55
+ private:
56
+ TrieNode* root = nullptr ;
57
+
58
+ private:
59
+ void buildTrie (const vector<int >& nums)
60
+ {
61
+ for (auto num : nums)
62
+ {
63
+ TrieNode* head = root;
64
+ for (int i = 1 , ptr = 0x40000000 ; i < 32 ; ++i, ptr >>= 1 )
65
+ {
66
+ if (ptr & num)
67
+ {
68
+ if (head->right == nullptr )
69
+ {
70
+ TrieNode* node = new TrieNode ();
71
+ head->right = node;
72
+ }
73
+ head = head->right ;
74
+ }
75
+ else
76
+ {
77
+ if (head->left == nullptr )
78
+ {
79
+ TrieNode* node = new TrieNode ();
80
+ head->left = node;
81
+ }
82
+ head = head->left ;
83
+ }
84
+ }
85
+ }
86
+ }
87
+
88
+ void clear (TrieNode* root)
89
+ {
90
+ if (root == nullptr ) return ;
91
+ clear (root->left );
92
+ clear (root->right );
93
+ delete root;
94
+ }
95
+ };
0 commit comments