LeetCode 题解工作台

按位与结果大于零的最长组合

对数组 nums 执行 按位与 相当于对数组 nums 中的所有整数执行 按位与 。 例如,对 nums = [1, 5, 3] 来说,按位与等于 1 & 5 & 3 = 1 。 同样,对 nums = [7] 而言,按位与等于 7 。 给你一个正整数数组 candidates 。计算 candid…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

题目需要找到按位与结果大于 的数字组合的最大长度,那么说明一定存在某个二进制位,所有数字在这个二进制位上都是 。因此,我们可以枚举每个二进制位,统计所有数字在这个二进制位上的 的个数,最后取最大值即可。 时间复杂度 $O(n \times \log M)$,其中 和 分别是数组 的长度和数组中的最大值。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

对数组 nums 执行 按位与 相当于对数组 nums 中的所有整数执行 按位与

  • 例如,对 nums = [1, 5, 3] 来说,按位与等于 1 & 5 & 3 = 1
  • 同样,对 nums = [7] 而言,按位与等于 7

给你一个正整数数组 candidates 。计算 candidates 中的数字每种组合下 按位与 的结果。

返回按位与结果大于 0最长 组合的长度

 

示例 1:

输入:candidates = [16,17,71,62,12,24,14]
输出:4
解释:组合 [16,17,62,24] 的按位与结果是 16 & 17 & 62 & 24 = 16 > 0 。
组合长度是 4 。
可以证明不存在按位与结果大于 0 且长度大于 4 的组合。
注意,符合长度最大的组合可能不止一种。
例如,组合 [62,12,24,14] 的按位与结果是 62 & 12 & 24 & 14 = 8 > 0 。

示例 2:

输入:candidates = [8,8]
输出:2
解释:最长组合是 [8,8] ,按位与结果 8 & 8 = 8 > 0 。
组合长度是 2 ,所以返回 2 。

 

提示:

  • 1 <= candidates.length <= 105
  • 1 <= candidates[i] <= 107
lightbulb

解题思路

方法一:位运算

题目需要找到按位与结果大于 00 的数字组合的最大长度,那么说明一定存在某个二进制位,所有数字在这个二进制位上都是 11。因此,我们可以枚举每个二进制位,统计所有数字在这个二进制位上的 11 的个数,最后取最大值即可。

时间复杂度 O(n×logM)O(n \times \log M),其中 nnMM 分别是数组 candidates\textit{candidates} 的长度和数组中的最大值。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
class Solution:
    def largestCombination(self, candidates: List[int]) -> int:
        ans = 0
        for i in range(max(candidates).bit_length()):
            ans = max(ans, sum(x >> i & 1 for x in candidates))
        return ans
speed

复杂度分析

指标
时间complexity is O(n * b) where b is the number of bits in the maximum integer, effectively O(n) since b is small and constant. Space complexity is O(1) because the bit count array uses fixed space independent of input size.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for an efficient solution avoiding full subset enumeration.

  • question_mark

    Expect bitwise operations and counting techniques rather than brute force.

  • question_mark

    They may hint at using a hash or counter for each bit position.

warning

常见陷阱

外企场景
  • error

    Trying to compute bitwise AND for all possible subsets, which is exponential.

  • error

    Ignoring that the AND must be greater than zero and including numbers without the required bit.

  • error

    Miscounting bits or failing to handle large arrays efficiently.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the largest combination where bitwise OR meets a certain threshold.

  • arrow_right_alt

    Count the number of combinations where a specific bit is set across all numbers.

  • arrow_right_alt

    Determine the smallest combination where the bitwise AND is non-zero.

help

常见问题

外企场景

按位与结果大于零的最长组合题解:数组·哈希·扫描 | LeetCode #2275 中等