@@ -959,3 +959,100 @@ dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i])
959959 return dp[prices. length- 1 ][0 ];
960960 }
961961```
962+
963+
964+
965+ ### 421. 数组中两个数的最大异或值
966+
967+ https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/
968+
969+ 给定一个非空数组,数组中元素为 a0, a1, a2, … , an-1,其中 0 ≤ ai < 231 。
970+
971+ 找到 ai 和aj 最大的异或 (XOR) 运算结果,其中0 ≤ i, j < n 。
972+
973+ 你能在O(n)的时间解决这个问题吗?
974+
975+ 示例:
976+
977+ 输入: [ 3, 10, 5, 25, 2, 8]
978+
979+ 输出: 28
980+
981+ 解释: 最大的结果是 5 ^ 25 = 28
982+
983+
984+
985+ ``` java
986+ public static class TreeNode {
987+ public int val;
988+ public TreeNode left = null ;
989+ public TreeNode right = null ;
990+ public TreeNode (int val ) {
991+ this . val = val;
992+ }
993+ }
994+
995+ Integer findMaximumXOR(int [] array) {
996+ if (array== null || array. length== 0 ) {
997+ return null ;
998+ }
999+ TreeNode root = new TreeNode (- 1 );
1000+ // 构建前缀树
1001+ for (int i = 0 ; i < array. length; i++ ) {
1002+ insert(root,array[i]);
1003+ }
1004+ int max = 0 ;
1005+
1006+ for (int i = 0 ; i < array. length; i++ ) {
1007+ int result = findMaxForTheValue(root,array[i]);
1008+ if (result> max){
1009+ max= result;
1010+ }
1011+ }
1012+ return max;
1013+ }
1014+
1015+ void insert(TreeNode root, int insertValue) {
1016+ // 最大值是是2的31次方
1017+ int bitValue = 1 << 30 ;
1018+ TreeNode currentNode = root;
1019+ while (bitValue!= 0 ) {
1020+ int result = insertValue & bitValue;
1021+ if (result== 0 ) {// array[i]这一位是0,往左创建节点
1022+ if (currentNode. left== null ) {
1023+ TreeNode node = new TreeNode (- 1 );
1024+ currentNode. left = node;
1025+ }
1026+ currentNode = currentNode. left;
1027+ } else {// array[i]这一位是1,往右边创建节点
1028+ if (currentNode. right== null ) {
1029+ TreeNode node = new TreeNode (- 1 );
1030+ currentNode. right = node;
1031+ }
1032+ currentNode = currentNode. right;
1033+ }
1034+ bitValue= bitValue>> 1 ;
1035+ }
1036+ currentNode. val = insertValue;
1037+ }
1038+
1039+ int findMaxForTheValue(TreeNode root, int value) {
1040+ TreeNode currentNode = root;
1041+ int bitValue = 1 << 30 ;
1042+ while (bitValue!= 0 ) {
1043+ int result = value & bitValue;
1044+ if (result== 0 ) {// array[i]这一位是0,往右边找节点
1045+
1046+ currentNode = currentNode. right != null ?
1047+ currentNode. right : currentNode. left;
1048+
1049+ } else {// array[i]这一位是1,往左边找节点
1050+ currentNode = currentNode. left != null ?
1051+ currentNode. left : currentNode. right;
1052+ }
1053+ bitValue= bitValue>> 1 ;
1054+ }
1055+ int result = value^ currentNode. val;
1056+ return result;
1057+ }
1058+ ```
0 commit comments