From d4bba90c1bb26ca180b5553e01fa507dce4e902e Mon Sep 17 00:00:00 2001 From: Kirito <1362050620@qq.com> Date: Wed, 14 Sep 2022 04:04:28 +0800 Subject: [PATCH] Create 421.cpp --- LeetCode/421.cpp | 89 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 LeetCode/421.cpp diff --git a/LeetCode/421.cpp b/LeetCode/421.cpp new file mode 100644 index 0000000..d36b552 --- /dev/null +++ b/LeetCode/421.cpp @@ -0,0 +1,89 @@ +class Trie { +public: + struct Node + { + bool ends; + int number; + Node* next[2]; + + Node() + { + ends = false; + memset(next, 0, sizeof(next)); + } + }; + Node* root; + + Trie() { + root = new Node; + } + + inline void stepDownInsert(int* bits, int leftBits, int number, Node* current) { + if (!leftBits) { + current->ends = true; + current->number = number; + return; + } + + if (!current->next[bits[leftBits - 1]]) { + auto n = new Node; + current->next[bits[leftBits - 1]] = n; + } + stepDownInsert(bits, leftBits - 1, number, current->next[bits[leftBits - 1]]); + } + + void insert(int number) { + int bits[32] = { 0 }; + int input = number; + int index = 0; + while (input) { + bits[index++] = input & 0x1; + input >>= 1; + } + stepDownInsert(bits, 31, number, root); + } +}; + +class Solution { +public: + Trie t; + + int findMaximumXOR(vector& nums) { + for (auto& n : nums) { + t.insert(n); + } + + int maxResult = 0; + + for (auto& n : nums) { + int bits[32] = { 0 }; + int input = n; + int index = 0; + while (input) { + bits[index++] = input & 0x1; + input >>= 1; + } + + auto current = t.root; + int result = 0; + for (int i = 30; i >= 0; i--) { + result <<= 1; + if (bits[i] && current->next[0]) { + current = current->next[0]; + result++; + } + else if (!bits[i] && current->next[1]) { + current = current->next[1]; + result++; + } + else { + current = current->next[0] ? current->next[0] : current->next[1]; + } + } + + maxResult = max(maxResult, result); + } + + return maxResult; + } +};