LeetCode 题解工作台

统计公平数对的数目

给你一个下标从 0 开始、长度为 n 的整数数组 nums ,和两个整数 lower 和 upper ,返回 公平数对的数目 。 如果 (i, j) 数对满足以下情况,则认为它是一个 公平数对 : 0 ,且 lower 示例 1: 输入: nums = [0,1,7,4,4,5], lower = …

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·搜索·答案·空间

bolt

答案摘要

我们先对数组 `nums` 按照升序排序,然后枚举 `nums[i]`,对于每个 `nums[i]`,我们通过二分查找找到 `nums[j]` 的下界 `j`,即第一个满足 `nums[j] >= lower - nums[i]` 的下标,然后再通过二分查找找到 `nums[k]` 的下界 `k`,即第一个满足 `nums[k] >= upper - nums[i] + 1` 的下标,那么 `[j…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始、长度为 n 的整数数组 nums ,和两个整数 lower 和 upper ,返回 公平数对的数目

如果 (i, j) 数对满足以下情况,则认为它是一个 公平数对 :

  • 0 <= i < j < n,且
  • lower <= nums[i] + nums[j] <= upper

 

示例 1:

输入:nums = [0,1,7,4,4,5], lower = 3, upper = 6
输出:6
解释:共计 6 个公平数对:(0,3)、(0,4)、(0,5)、(1,3)、(1,4) 和 (1,5) 。

示例 2:

输入:nums = [1,7,9,2,5], lower = 11, upper = 11
输出:1
解释:只有单个公平数对:(2,3) 。

 

提示:

  • 1 <= nums.length <= 105
  • nums.length == n
  • -109 <= nums[i] <= 109
  • -109 <= lower <= upper <= 109
lightbulb

解题思路

方法一:排序 + 二分查找

我们先对数组 nums 按照升序排序,然后枚举 nums[i],对于每个 nums[i],我们通过二分查找找到 nums[j] 的下界 j,即第一个满足 nums[j] >= lower - nums[i] 的下标,然后再通过二分查找找到 nums[k] 的下界 k,即第一个满足 nums[k] >= upper - nums[i] + 1 的下标,那么 [j, k) 即为 nums[j] 满足 lower <= nums[i] + nums[j] <= upper 的下标范围,这些下标对应的 nums[j] 的个数即为 k - j,将其累加到答案中即可。注意 j>ij \gt i

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为数组 nums 的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
        nums.sort()
        ans = 0
        for i, x in enumerate(nums):
            j = bisect_left(nums, lower - x, lo=i + 1)
            k = bisect_left(nums, upper - x + 1, lo=i + 1)
            ans += k - j
        return ans
speed

复杂度分析

指标
时间O(n \log n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Sorting the array is likely expected before counting pairs.

  • question_mark

    Look for using binary search to find the lower and upper sum bounds efficiently.

  • question_mark

    Handling edge cases where multiple elements produce the same sum is important.

warning

常见陷阱

外企场景
  • error

    Failing to sort nums first, which breaks binary search assumptions.

  • error

    Incorrectly counting pairs when i >= j or double counting identical sums.

  • error

    Ignoring the constraints leading to solutions that exceed time limits for large n.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count fair pairs where nums[i]*nums[j] falls within a range instead of sum.

  • arrow_right_alt

    Find fair pairs allowing i <= j instead of i < j, adjusting counting logic.

  • arrow_right_alt

    Return the actual list of fair pairs instead of just the count.

help

常见问题

外企场景

统计公平数对的数目题解:二分·搜索·答案·空间 | LeetCode #2563 中等