LeetCode 题解工作台
查询数组异或美丽值
给你一个下标从 0 开始的整数数组 nums 。 三个下标 i , j 和 k 的 有效值 定义为 ((nums[i] | nums[j]) & nums[k]) 。 一个数组的 异或美丽值 是数组中所有满足 0 的三元组 (i, j, k) 的 有效值 的异或结果。 请你返回 nums 的异或美丽…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们首先考虑 与 不相等的情况,此时 `((nums[i] | nums[j]) & nums[k])` 与 `((nums[j] | nums[i]) & nums[k])` 的结果是相同的,两者的异或结果为 。 因此,我们只需要考虑 与 相等的情况。此时 `((nums[i] | nums[j]) & nums[k]) = (nums[i] & nums[k])`,如果 $i \neq…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 。
三个下标 i ,j 和 k 的 有效值 定义为 ((nums[i] | nums[j]) & nums[k]) 。
一个数组的 异或美丽值 是数组中所有满足 0 <= i, j, k < n 的三元组 (i, j, k) 的 有效值 的异或结果。
请你返回 nums 的异或美丽值。
注意:
val1 | val2是val1和val2的按位或。val1 & val2是val1和val2的按位与。
示例 1:
输入:nums = [1,4] 输出:5 解释: 三元组和它们对应的有效值如下: - (0,0,0) 有效值为 ((1 | 1) & 1) = 1 - (0,0,1) 有效值为 ((1 | 1) & 4) = 0 - (0,1,0) 有效值为 ((1 | 4) & 1) = 1 - (0,1,1) 有效值为 ((1 | 4) & 4) = 4 - (1,0,0) 有效值为 ((4 | 1) & 1) = 1 - (1,0,1) 有效值为 ((4 | 1) & 4) = 4 - (1,1,0) 有效值为 ((4 | 4) & 1) = 0 - (1,1,1) 有效值为 ((4 | 4) & 4) = 4 数组的异或美丽值为所有有效值的按位异或 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5 。
示例 2:
输入:nums = [15,45,20,2,34,35,5,44,32,30]
输出:34
解释:数组的异或美丽值为 34 。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 109
解题思路
方法一:位运算
我们首先考虑 与 不相等的情况,此时 ((nums[i] | nums[j]) & nums[k]) 与 ((nums[j] | nums[i]) & nums[k]) 的结果是相同的,两者的异或结果为 。
因此,我们只需要考虑 与 相等的情况。此时 ((nums[i] | nums[j]) & nums[k]) = (nums[i] & nums[k]),如果 ,那么与 nums[k] & nums[i] 的结果是相同的,这些值的异或结果为 。
因此,我们最终只需要考虑 的情况,那么答案就是所有 的异或结果。
时间复杂度 ,空间复杂度 。其中 为数组的长度。
class Solution:
def xorBeauty(self, nums: List[int]) -> int:
return reduce(xor, nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check for the candidate's understanding of bitwise operations and their ability to identify optimization opportunities.
- question_mark
Evaluate whether the candidate can recognize the trade-off between brute force and optimized solutions.
- question_mark
Assess the candidate's ability to explain their approach clearly and in detail.
常见陷阱
外企场景- error
Not simplifying the XOR expression leads to inefficient solutions.
- error
Overcomplicating the solution by missing opportunities for bitwise optimization.
- error
Neglecting edge cases such as when the array contains only one element.
进阶变体
外企场景- arrow_right_alt
Consider variants where the XOR expression is changed to use other bitwise operators.
- arrow_right_alt
Implement a solution where the array is sorted first to see how it affects performance.
- arrow_right_alt
Change the problem to compute a different bitwise combination or condition between indices.