Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.
- Example 1:
- Input: nums = [3,10,5,25,2,8]
- Output: 28
- Explanation: The maximum result is 5 XOR 25 = 28.
- Example 2:
- Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
- Output: 127
- Constraints:
- 1 <= nums.length <= 2 * 10^5
- 0 <= nums[i] <= 2^31 - 1
- */
- struct BIT_TrieNode{
- BIT_TrieNode* children[2];
- BIT_TrieNode(){
- this->children[0]=NULL;
- this->children[1]=NULL;
- }
- };
- class Solution {
- private:
- BIT_TrieNode* root;
- public:
- void insert(int num){
- BIT_TrieNode* pCrawl=root;
- for(int i=31;i>=0;i--){
- int bit_state=(num >> i) & 1; // CHECK IF ith bit is 1 or 0
- if(pCrawl->children[bit_state]==NULL){
- pCrawl->children[bit_state]=new BIT_TrieNode();
- }
- pCrawl=pCrawl->children[bit_state];
- }
- }
- int query(int num){
- BIT_TrieNode* pCrawl=root;
- int res=0;
- for(int i=31;i>=0;i--){
- int bit_state=(num >> i) & 1;
- if(pCrawl->children[bit_state^1]!=NULL){ // check if opposite bit is available, if yes, go for it since different bit results in 1 in XOR
- pCrawl=pCrawl->children[bit_state^1];
- res=res | (1 << i); // turning bit on
- }
- else{
- pCrawl=pCrawl->children[bit_state];
- }
- }
- return res;
- }
- int findMaximumXOR(vector<int>& nums) {
- root=new BIT_TrieNode();
- int res=0;
- for(auto x: nums){
- insert(x);
- }
- for(auto x: nums){
- res=max(res,query(x)); // the thought process is that we already made the trie using bits, now for example 1 we know binary of 5 is 00000000000000000000000000000101 in 32 bit format. So, while iterating on this binary rep of 5, if we get a 1 we should take that as we see in query. We always try to take the opposite bit of the current bit as this will result in 1 and give max XOR
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment