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

This commit is contained in:
huangge1199@hotmail.com 2021-05-16 19:50:56 +08:00
parent 3303fa2d7a
commit 21d58217d4
2 changed files with 151 additions and 0 deletions

View File

@ -0,0 +1,97 @@
//给你一个整数数组 nums 返回 nums[i] XOR nums[j] 的最大运算结果其中 0 i j < n
//
// 进阶你可以在 O(n) 的时间解决这个问题吗
//
//
//
//
//
// 示例 1
//
//
//输入nums = [3,10,5,25,2,8]
//输出28
//解释最大运算结果是 5 XOR 25 = 28.
//
// 示例 2
//
//
//输入nums = [0]
//输出0
//
//
// 示例 3
//
//
//输入nums = [2,4]
//输出6
//
//
// 示例 4
//
//
//输入nums = [8,10,2]
//输出10
//
//
// 示例 5
//
//
//输入nums = [14,70,53,83,49,91,36,80,92,51,66,70]
//输出127
//
//
//
//
// 提示
//
//
// 1 <= nums.length <= 2 * 104
// 0 <= nums[i] <= 231 - 1
//
//
//
// Related Topics 位运算 字典树
// 👍 324 👎 0
package leetcode.editor.cn;
import java.util.HashSet;
import java.util.Set;
//421:数组中两个数的最大异或值
public class MaximumXorOfTwoNumbersInAnArray {
public static void main(String[] args) {
//测试代码
Solution solution = new MaximumXorOfTwoNumbersInAnArray().new Solution();
System.out.println();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findMaximumXOR(int[] nums) {
int x = 0;
for (int k = 30; k >= 0; k--) {
Set<Integer> set = new HashSet<>();
boolean found = false;
for (int num : nums) {
set.add(num >> k);
if (set.contains(((x << 1) + 1) ^ (num >> k))) {
found = true;
break;
}
}
x <<= 1;
if (found) {
x++;
}
}
return x;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,54 @@
<p>给你一个整数数组 <code>nums</code> ,返回<em> </em><code>nums[i] XOR nums[j]</code> 的最大运算结果,其中 <code>0 ≤ i ≤ j < n</code></p>
<p><strong>进阶:</strong>你可以在 <code>O(n)</code> 的时间解决这个问题吗?</p>
<p> </p>
<div class="original__bRMd">
<div>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>nums = [3,10,5,25,2,8]
<strong>输出:</strong>28
<strong>解释:</strong>最大运算结果是 5 XOR 25 = 28.</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>nums = [0]
<strong>输出:</strong>0
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>nums = [2,4]
<strong>输出:</strong>6
</pre>
<p><strong>示例 4</strong></p>
<pre>
<strong>输入:</strong>nums = [8,10,2]
<strong>输出:</strong>10
</pre>
<p><strong>示例 5</strong></p>
<pre>
<strong>输入:</strong>nums = [14,70,53,83,49,91,36,80,92,51,66,70]
<strong>输出:</strong>127
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
</div>
</div>
<div><div>Related Topics</div><div><li>位运算</li><li>字典树</li></div></div>\n<div><li>👍 316</li><li>👎 0</li></div>