1 Star 0 Fork 0

luobg01/PFJ_coding

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
code08_findMaximumXOR.h 1.66 KB
一键复制 编辑 原始数据 按行查看 历史
luobg01 提交于 2023-07-22 11:07 . add code first
//
// Created by 罗炳国 on 2023/7/19.
//
#ifndef PFJ_CODE08_FINDMAXIMUMXOR_H
#define PFJ_CODE08_FINDMAXIMUMXOR_H
#include "commonHeader.h"
/**
* 给你一个整数数组 nums ,返回 nums[i] XOR nums[j] 的最大运算结果,其中 0 ≤ i ≤ j < n 。
* https://leetcode.cn/problems/maximum-xor-of-two-numbers-in-an-array/
* */
struct node {
node() {
for (int i = 0; i < 2; i++)
next[i] = nullptr;
}
struct node *next[2];
};
class numTrie {
public:
void add(int num) {
node *cur = &head;
for (int off = 31; off >= 0; off--) {
// 取出第off位的path
int path = (num >> off) & 1;
cur->next[path] = cur->next[path] == nullptr ? new node : cur->next[path];
cur = cur->next[path];
}
}
int maxXor(int num) {
node *cur = &head;
int ans = 0;
for (int off = 31; off >= 0; off--) {
int path = (num >> off) & 1;
// 期待最优路径
int best = off == 31 ? path : (path ^ 1);
// 实际遇到的
best = cur->next[best] == nullptr ? (best ^ 1) : best;
ans |= (best ^ path) << off;
cur = cur->next[best];
}
return ans;
}
private:
node head;
};
class code08_findMaximumXOR {
public:
int findMaximumXOR(vector<int>& nums) {
int ans = INT32_MIN, N = nums.size();
if (N < 2) return 0;
numTrie trie;
trie.add(nums[0]);
for (int i = 1; i < N; i++) {
ans = max(ans, trie.maxXor(nums[i]));
trie.add(nums[i]);
}
return ans;
}
};
#endif //PFJ_CODE08_FINDMAXIMUMXOR_H
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/luobg01/pfj_coding.git
git@gitee.com:luobg01/pfj_coding.git
luobg01
pfj_coding
PFJ_coding
master

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385