LeetCode 题解工作台
不同 XOR 三元组的数目 I
给你一个长度为 n 的整数数组 nums ,其中 nums 是范围 [1, n] 内所有数的 排列 。 XOR 三元组 定义为三个元素的异或值 nums[i] XOR nums[j] XOR nums[k] ,其中 i 。 返回所有可能三元组 (i, j, k) 中 不同 的 XOR 值的数量。 排…
3
题型
0
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个长度为 n 的整数数组 nums,其中 nums 是范围 [1, n] 内所有数的 排列 。
XOR 三元组 定义为三个元素的异或值 nums[i] XOR nums[j] XOR nums[k],其中 i <= j <= k。
返回所有可能三元组 (i, j, k) 中 不同 的 XOR 值的数量。
排列 是一个集合中所有元素的重新排列。
示例 1:
输入: nums = [1,2]
输出: 2
解释:
所有可能的 XOR 三元组值为:
(0, 0, 0) → 1 XOR 1 XOR 1 = 1(0, 0, 1) → 1 XOR 1 XOR 2 = 2(0, 1, 1) → 1 XOR 2 XOR 2 = 1(1, 1, 1) → 2 XOR 2 XOR 2 = 2
不同的 XOR 值为 {1, 2},因此输出为 2。
示例 2:
输入: nums = [3,1,2]
输出: 4
解释:
可能的 XOR 三元组值包括:
(0, 0, 0) → 3 XOR 3 XOR 3 = 3(0, 0, 1) → 3 XOR 3 XOR 1 = 1(0, 0, 2) → 3 XOR 3 XOR 2 = 2(0, 1, 2) → 3 XOR 1 XOR 2 = 0
不同的 XOR 值为 {0, 1, 2, 3},因此输出为 4。
提示:
1 <= n == nums.length <= 1051 <= nums[i] <= nnums是从1到n的整数的一个排列。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity can range from O(n^3) for naive triple iteration to O(n^2) or O(n) using prefix XOR and mathematical insights. Space complexity ranges from O(n) for prefix arrays to O(n^2) for storing unique XOR values depending on the approach. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Notice if candidate identifies the permutation property and its impact on XOR results.
- question_mark
Check if they optimize nested loops using prefix XOR or other bitwise properties.
- question_mark
Observe whether they consider duplicate elimination and efficient unique counting.
常见陷阱
外企场景- error
Forgetting that triplet indices must satisfy i <= j <= k, causing incorrect counts.
- error
Overlooking repeated XOR values and failing to track unique results.
- error
Assuming a simple formula for XOR count without considering array permutation constraints.
进阶变体
外企场景- arrow_right_alt
Count unique XOR pairs instead of triplets.
- arrow_right_alt
Allow arrays with repeated elements rather than strict permutations.
- arrow_right_alt
Compute maximum XOR value among all triplets instead of counting unique results.