Skip to content

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

https://leetcode.cn/problems/largest-combination-with-bitwise-and-greater-than-zero/

对数组 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 <= 10^5
  • 1 <= candidates[i] <= 10^7

找出所有整数在二进制表示中,任意位上为1的最大共同出现次数。

逐位计算:遍历所有存在该位为 1 元素的二进制位,并统计对应位数值为 1 的元素个数及最大值。对于二进制位的范围,由于 candidates 中的整数的取值范围均在 [1,10^7] 闭区间内,同时我们有 223<107<224,因此只需要遍历最低的 24 个二进制位即可。

python
class Solution:
    def largestCombination(self, candidates: List[int]) -> int:
        # 初始化一个列表来记录每一位为1的数量
        bit_counts = [0] * 24
        
        # 遍历每个数字并更新每一位的计数
        for num in candidates:
            for i in range(24):
                if num & (1 << i):
                    bit_counts[i] += 1
        
        # 返回最大值
        return max(bit_counts)

用内置函数bin(),进一步优化

python
class Solution:
    def largestCombination(self, candidates: List[int]) -> int:
        bit_counts = [0] * 24

        for num in candidates:
            binary_str = bin(num)[2:][::-1]
            for i, bit in enumerate(binary_str):
                if bit == '1':
                    bit_counts[i] += 1

        return max(bit_counts)