Given a non-empty array, the elements in the array are a0, a1, a2,... an-1, where 0 < AI < 231.
Find the largest XOR operation results of ai and aj, where 0 < i, J < n.
Can you solve this problem in O(n) time?
Example:
Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The biggest result is 5 ^ 25 = 28.
Thought analysis: This kind of question does not need the violence law, designates the surname to say to want O(n). Use tree building as prompted.
First of all, we need to know that the binary high-level 1 will be greater than the low-level all and, for example, "11111111111" the highest representative of the "1" expansion by weight 128, while the latter "11111111" expansion by weight and only 127. Therefore, we should try our best to choose the "1" as the result of XOR.
Step 1: Traveling through the array, we follow the binary [31, 30,... 1, 0] The status of each person is built, left is placed 0, right is placed 1. For example, the binary of an int number is "0110110... "We need to put it in [left, right, right, left, right, left... ].
The second step: traversing the array, according to the greedy strategy, try to maintain the direction of the current choice to ensure that the current capacity is different or the result is 1.
class Solution { public: struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; int findMaximumXOR(vector<int>& nums) { TreeNode *root = new TreeNode(-1); int maxRes = 0; //Establishment of Binary Trees for (auto num : nums){ TreeNode *treePtr = root; //According to the bit 0 and 1 of the binary digit string [31,30,.... 1,0], put 1 on the left and 0 on the right. //Gradual detection from high to low, recursive search for placement for (int i = 31; i >= 0; --i){ if ((num & (1 << i)) == 0){ //num has a position i of 0 and needs to be left at the current node if (treePtr->left == NULL){ treePtr->left = new TreeNode(0); } treePtr = treePtr->left;//Transfer to left for i + 1 placement } else{ //num has a position i of 1 and needs to be placed at the right of the current node if (treePtr->right == NULL){ treePtr->right = new TreeNode(1); } treePtr = treePtr->right;//Move to right and place i + 1 } } //Finally, the left position of the bottom node treePtr->left = new TreeNode(num); } //search for (auto num : nums){ TreeNode *treePtr = root; //Search from high to low, greedy strategy, try to maintain the current position or 1 for (int i = 31; i >= 0; --i){ if ((num & (1 << i)) == 0){ //If num's i-bit 0, you should choose right first, because right is 1, so 1 ^ 0 = 1 if (treePtr->right != NULL){ treePtr = treePtr->right; } else{ treePtr = treePtr->left; } } else{ //If this bit is 1, you should choose left first. if (treePtr->left != NULL){ treePtr = treePtr->left; } else{ treePtr = treePtr->right; } } } //Finally, remove the bottom left for XOR operation maxRes = max(maxRes, treePtr->left->val ^ num); } return maxRes; } };