421.数组中两个数的最大异或值 优化
This commit is contained in:
parent
1da014d08e
commit
352bb7307a
|
@ -1,10 +1,7 @@
|
|||
use crate::Solution;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Default)]
|
||||
struct Trie {
|
||||
left: Option<Box<Trie>>,
|
||||
right: Option<Box<Trie>>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Trie(Option<Box<Trie>>, Option<Box<Trie>>);
|
||||
|
||||
impl Trie {
|
||||
fn new() -> Self {
|
||||
|
@ -12,14 +9,11 @@ impl Trie {
|
|||
}
|
||||
|
||||
fn insert(&mut self, num: i32) {
|
||||
let mut node = self;
|
||||
for k in (0..31).rev() {
|
||||
node = if ((num >> k) & 1) == 0 {
|
||||
node.left.get_or_insert(Box::new(Trie::new()))
|
||||
} else {
|
||||
node.right.get_or_insert(Box::new(Trie::new()))
|
||||
}
|
||||
}
|
||||
(0..31).rev().fold(self, |node, k|
|
||||
match (num >> k) & 1 {
|
||||
0 => node.0.get_or_insert_with(Default::default),
|
||||
_ => node.1.get_or_insert_with(Default::default)
|
||||
});
|
||||
}
|
||||
|
||||
fn check(&self, num: i32) -> i32 {
|
||||
|
@ -27,18 +21,18 @@ impl Trie {
|
|||
let mut x = 0;
|
||||
for k in (0..31).rev() {
|
||||
if ((num >> k) & 1) == 0 {
|
||||
if let Some(r) = &c.right {
|
||||
if let Some(r) = &c.1 {
|
||||
c = r;
|
||||
x = (x << 1) + 1;
|
||||
} else if let Some(l) = &c.left {
|
||||
} else if let Some(l) = &c.0 {
|
||||
c = l;
|
||||
x <<= 1;
|
||||
}
|
||||
} else {
|
||||
if let Some(l) = &c.left {
|
||||
if let Some(l) = &c.0 {
|
||||
c = l;
|
||||
x = (x << 1) + 1;
|
||||
} else if let Some(r) = &c.right {
|
||||
} else if let Some(r) = &c.1 {
|
||||
c = r;
|
||||
x <<= 1;
|
||||
}
|
||||
|
@ -49,9 +43,7 @@ impl Trie {
|
|||
}
|
||||
|
||||
impl Solution {
|
||||
/// 421.数组中两个数的最大异或值
|
||||
///
|
||||
/// [原题链接](https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/)
|
||||
/// [421.数组中两个数的最大异或值](https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/)
|
||||
///
|
||||
/// 2021-05-16 22:13:21
|
||||
///
|
||||
|
@ -98,9 +90,6 @@ impl Solution {
|
|||
/// ```
|
||||
/// # 方法2
|
||||
/// 字典树
|
||||
///
|
||||
/// # 方法3
|
||||
/// 哈希 todo
|
||||
pub fn find_maximum_xor(nums: Vec<i32>) -> i32 {
|
||||
let mut x = 0;
|
||||
let mut trie = Trie::new();
|
||||
|
|
Loading…
Reference in New Issue