LeetCode 题解工作台

优质数对的数目

给你一个下标从 0 开始的正整数数组 nums 和一个正整数 k 。 如果满足下述条件,则数对 (num1, num2) 是 优质数对 : num1 和 num2 都 在数组 nums 中存在。 num1 OR num2 和 num1 AND num2 的二进制表示中值为 1 的位数之和大于等于 k…

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 数组·哈希·扫描

bolt

答案摘要

class Solution: def countExcellentPairs(self, nums: List[int], k: int) -> int:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的正整数数组 nums 和一个正整数 k

如果满足下述条件,则数对 (num1, num2)优质数对

  • num1num2 在数组 nums 中存在。
  • num1 OR num2num1 AND num2 的二进制表示中值为 1 的位数之和大于等于 k ,其中 OR 是按位 操作,而 AND 是按位 操作。

返回 不同 优质数对的数目。

如果 a != c 或者 b != d ,则认为 (a, b)(c, d) 是不同的两个数对。例如,(1, 2)(2, 1) 不同。

注意:如果 num1 在数组中至少出现 一次 ,则满足 num1 == num2 的数对 (num1, num2) 也可以是优质数对。

 

示例 1:

输入:nums = [1,2,3,1], k = 3
输出:5
解释:有如下几个优质数对:
- (3, 3):(3 AND 3) 和 (3 OR 3) 的二进制表示都等于 (11) 。值为 1 的位数和等于 2 + 2 = 4 ,大于等于 k = 3 。
- (2, 3) 和 (3, 2): (2 AND 3) 的二进制表示等于 (10) ,(2 OR 3) 的二进制表示等于 (11) 。值为 1 的位数和等于 1 + 2 = 3 。
- (1, 3) 和 (3, 1): (1 AND 3) 的二进制表示等于 (01) ,(1 OR 3) 的二进制表示等于 (11) 。值为 1 的位数和等于 1 + 2 = 3 。
所以优质数对的数目是 5 。

示例 2:

输入:nums = [5,1,1], k = 10
输出:0
解释:该数组中不存在优质数对。

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 60
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def countExcellentPairs(self, nums: List[int], k: int) -> int:
        s = set(nums)
        ans = 0
        cnt = Counter()
        for v in s:
            cnt[v.bit_count()] += 1
        for v in s:
            t = v.bit_count()
            for i, x in cnt.items():
                if t + i >= k:
                    ans += x
        return ans
speed

复杂度分析

指标
时间complexity is O(n log n) due to sorting and binary search over unique bit counts, space complexity is O(n) to store counts and hash map entries.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for handling duplicates correctly to prevent overcounting.

  • question_mark

    Expect candidates to optimize bit counting rather than comparing numbers directly.

  • question_mark

    Check if the candidate uses array scanning plus hash lookup efficiently for large n.

warning

常见陷阱

外企场景
  • error

    Failing to deduplicate nums before counting excellent pairs, which inflates results.

  • error

    Using nested loops on all pairs leading to TLE for large arrays.

  • error

    Miscounting set bits or misunderstanding the combined AND and OR bit sum condition.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count excellent pairs where only the OR bits count towards k instead of AND plus OR.

  • arrow_right_alt

    Find excellent pairs in a multidimensional array or matrix using similar bit manipulation.

  • arrow_right_alt

    Compute excellent pairs with an added constraint on the difference between numbers.

help

常见问题

外企场景

优质数对的数目题解:数组·哈希·扫描 | LeetCode #2354 困难