首页 > 编程语言 > 详细

421. 数组中两个数的最大异或值

时间:2020-04-17 23:14:04      阅读:76      评论:0      收藏:0      [点我收藏+]
 1 struct Node
 2 {
 3     Node* next[2] = {nullptr};
 4 };
 5 
 6 class Solution 
 7 {
 8 public:
 9     void insert(int num, Node* root) 
10     {
11         for (int i = 30; i >= 0; --i) 
12         {
13             int t = (num >> i & 1);
14             if (!root->next[t]) root->next[t] = new Node();
15             root = root->next[t];
16         }
17     }
18 
19     int findMaximumXOR(vector<int>& nums) 
20     {
21         Node* root = new Node();
22         for (auto val : nums) insert(val, root);
23         
24         int res = 0, tmp = 0;
25         Node* p = root;
26         for (auto val : nums) 
27         {
28             p = root; 
29             tmp = 0;
30             for (int i = 30; i >= 0; --i) 
31             {
32                 int t = (val >> i) & 1;
33                 if (p->next[!t]) 
34                 {
35                     p = p->next[!t];
36                     tmp += (1 << i);
37                 }
38                 else p = p->next[t];
39             }
40             res = max(res, tmp);
41         }
42         return res;
43     }
44 };

 

421. 数组中两个数的最大异或值

原文:https://www.cnblogs.com/yuhong1103/p/12722648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!