查询数组异或美丽值
难度:
标签:
题目描述
You are given a 0-indexed integer array nums
.
The effective value of three indices i
, j
, and k
is defined as ((nums[i] | nums[j]) & nums[k])
.
The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k)
where 0 <= i, j, k < n
.
Return the xor-beauty of nums
.
Note that:
val1 | val2
is bitwise OR ofval1
andval2
.val1 & val2
is bitwise AND ofval1
andval2
.
Example 1:
Input: nums = [1,4] Output: 5 Explanation: The triplets and their corresponding effective values are listed below: - (0,0,0) with effective value ((1 | 1) & 1) = 1 - (0,0,1) with effective value ((1 | 1) & 4) = 0 - (0,1,0) with effective value ((1 | 4) & 1) = 1 - (0,1,1) with effective value ((1 | 4) & 4) = 4 - (1,0,0) with effective value ((4 | 1) & 1) = 1 - (1,0,1) with effective value ((4 | 1) & 4) = 4 - (1,1,0) with effective value ((4 | 4) & 1) = 0 - (1,1,1) with effective value ((4 | 4) & 4) = 4 Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.
Example 2:
Input: nums = [15,45,20,2,34,35,5,44,32,30]
Output: 34
Explanation: The xor-beauty of the given array is 34.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
代码结果
运行时间: 31 ms, 内存: 28.0 MB
/*
* 思路:
* 1. 使用 Java Stream API 来实现遍历所有的三元组组合 (i, j, k)。
* 2. 通过 mapToInt 操作将每个组合的有效值映射为整数,然后使用 reduce 操作计算所有有效值的异或结果。
*/
import java.util.stream.IntStream;
public class Solution {
public int xorBeauty(int[] nums) {
int n = nums.length;
return IntStream.range(0, n)
.flatMap(i -> IntStream.range(0, n)
.flatMap(j -> IntStream.range(0, n)
.map(k -> (nums[i] | nums[j]) & nums[k])))
.reduce(0, (a, b) -> a ^ b);
}
}
解释
方法:
这个题解直接计算了数组 `nums` 中所有元素的异或总和,忽略了题目中的复杂三元组运算条件。题目要求对于数组中的任意三元组 `(i, j, k)` 计算 `((nums[i] | nums[j]) & nums[k])` 的结果,并对所有这些结果进行异或。然而,这个题解仅仅对数组中的每个元素进行了异或运算,没有涉及到按位或和与运算。这表明题解可能误解了题目要求,或者是基于某种观察到的特性进行了简化处理,但没有在题解中提供这样的说明。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
题解中提到直接对数组元素进行异或操作,这与题目中定义的三元组运算 `(nums[i] | nums[j]) & nums[k]` 有何关联?
▷🦆
在题解中是否考虑了所有可能的三元组 `(i, j, k)` 组合,以及这些组合是如何影响最终的异或美丽值的?
▷🦆
题解中简化的处理方式是否有理论依据或者特定假设,能够确保结果的正确性?
▷