forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update 421.Maximum-XOR-of-Two-Numbers-in-an-Array.cpp
- Loading branch information
1 parent
eb22379
commit cd94b56
Showing
1 changed file
with
28 additions
and
47 deletions.
There are no files selected for viewing
75 changes: 28 additions & 47 deletions
75
...421.Maximum-XOR-of-Two-Numbers-in-an-Array/421.Maximum-XOR-of-Two-Numbers-in-an-Array.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,63 +1,44 @@ | ||
class Solution { | ||
public: | ||
class TrieNode | ||
{ | ||
public: | ||
TrieNode* next[2]; | ||
TrieNode() | ||
{ | ||
next[0]=NULL; | ||
next[1]=NULL; | ||
} | ||
TrieNode* next[2]; | ||
}; | ||
TrieNode* buildTree(vector<int>nums) | ||
public: | ||
int findMaximumXOR(vector<int>& nums) | ||
{ | ||
TrieNode* root=new TrieNode(); | ||
TrieNode* current; | ||
for (int i=0; i<nums.size(); i++) | ||
TrieNode* root = new TrieNode(); | ||
for (auto num: nums) | ||
{ | ||
current = root; | ||
for (int j=31; j>=0; j--) | ||
TrieNode* node = root; | ||
for (int k=31; k>=0; k--) | ||
{ | ||
int bit = ((nums[i]>>j)&1); | ||
if (current->next[bit]==NULL) | ||
current->next[bit]=new TrieNode(); | ||
current=current->next[bit]; | ||
if (node->next[(num>>k)&1]==NULL) | ||
node->next[(num>>k)&1] = new TrieNode(); | ||
node = node->next[(num>>k)&1]; | ||
} | ||
} | ||
return root; | ||
} | ||
|
||
int oppositePath(TrieNode* root, int num) | ||
{ | ||
TrieNode* node =root; | ||
int result=0; | ||
for (int i=31; i>=0; i--) | ||
|
||
int ret = 0; | ||
for (auto num: nums) | ||
{ | ||
int bit= (num>>i)&1; | ||
if (node->next[1-bit]!=NULL) | ||
{ | ||
node = node->next[1-bit]; | ||
result += (1-bit)<<i; | ||
} | ||
else | ||
TrieNode* node = root; | ||
int ans = 0; | ||
for (int k=31; k>=0; k--) | ||
{ | ||
node = node->next[bit]; | ||
result += (bit)<<i; | ||
if (node->next[1 - (num>>k)&1]!=NULL) | ||
{ | ||
ans = ans*2+1; | ||
node = node->next[1 - (num>>k)&1]; | ||
} | ||
else | ||
{ | ||
ans = ans*2+0; | ||
node = node->next[(num>>k)&1]; | ||
} | ||
} | ||
ret = max(ret, ans); | ||
} | ||
return result^num; | ||
} | ||
|
||
int findMaximumXOR(vector<int>& nums) | ||
{ | ||
TrieNode* root=buildTree(nums); | ||
int result=0; | ||
for (int i=0; i<nums.size(); i++) | ||
{ | ||
result = max(result, oppositePath(root,nums[i])); | ||
} | ||
return result; | ||
return ret; | ||
} | ||
}; |