LeetCode 题解工作台
找出数组中的 K-or 值
给你一个整数数组 nums 和一个整数 k 。让我们通过扩展标准的按位或来介绍 K-or 操作。在 K-or 操作中,如果在 nums 中,至少存在 k 个元素的第 i 位值为 1 ,那么 K-or 中的第 i 位的值是 1 。 返回 nums 的 K-or 值。 示例 1: 输入: nums = …
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·结合·位运算·操作
答案摘要
我们可以在 $[0, 32)$ 范围内枚举每一位 ,统计数组 有多少个数的第 位为 ,记为 。如果 $cnt \ge k$,那么我们就将 次方加到答案中。 枚举结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给你一个整数数组 nums 和一个整数 k 。让我们通过扩展标准的按位或来介绍 K-or 操作。在 K-or 操作中,如果在 nums 中,至少存在 k 个元素的第 i 位值为 1 ,那么 K-or 中的第 i 位的值是 1 。
返回 nums 的 K-or 值。
示例 1:
输入:nums = [7,12,9,8,9,15], k = 4 输出:9 解释: 用二进制表示 numbers:
| Number | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
|---|---|---|---|---|
| 7 | 0 | 1 | 1 | 1 |
| 12 | 1 | 1 | 0 | 0 |
| 9 | 1 | 0 | 0 | 1 |
| 8 | 1 | 0 | 0 | 0 |
| 9 | 1 | 0 | 0 | 1 |
| 15 | 1 | 1 | 1 | 1 |
| Result = 9 | 1 | 0 | 0 | 1 |
位 0 在 7, 9, 9, 15 中为 1。位 3 在 12, 9, 8, 9, 15 中为 1。 只有位 0 和 3 满足。结果是 (1001)2 = 9。
示例 2:
输入:nums = [2,12,1,11,4,5], k = 6 输出:0 解释:没有位在所有 6 个数字中都为 1,如 k = 6 所需要的。所以,答案为 0。
示例 3:
输入:nums = [10,8,5,9,11,6,8], k = 1 输出:15 解释:因为 k == 1 ,数组的 1-or 等于其中所有元素按位或运算的结果。因此,答案为 10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15 。
提示:
1 <= nums.length <= 500 <= nums[i] < 2311 <= k <= nums.length
解题思路
方法一:枚举
我们可以在 范围内枚举每一位 ,统计数组 有多少个数的第 位为 ,记为 。如果 ,那么我们就将 次方加到答案中。
枚举结束后,返回答案即可。
时间复杂度 ,其中 和 分别是数组 的长度以及 的最大值。空间复杂度 。
class Solution:
def findKOr(self, nums: List[int], k: int) -> int:
ans = 0
for i in range(32):
cnt = sum(x >> i & 1 for x in nums)
if cnt >= k:
ans |= 1 << i
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the candidate's ability to optimize the bit counting process.
- question_mark
Watch for efficient traversal strategies, avoiding repeated work.
- question_mark
Assess understanding of bitwise operations and how to combine results.
常见陷阱
外企场景- error
Misunderstanding the problem's rule for setting bits based on k occurrences.
- error
Failing to consider all bit positions, especially in larger numbers.
- error
Overcomplicating the solution when a simple bit-counting approach works.
进阶变体
外企场景- arrow_right_alt
Solve the problem for a larger array (nums.length > 50).
- arrow_right_alt
Optimize the solution to handle numbers with a bit length greater than 31.
- arrow_right_alt
Modify the problem to find the K-or for a dynamic range of k values.