📌  相关文章
📜  从绝对差不小于对中最小元素的数组中计数对(1)

📅  最后修改于: 2023-12-03 15:06:38.551000             🧑  作者: Mango

从绝对差不小于对中最小元素的数组中计数对
问题描述

给定一个整数数组,计算其中绝对差不小于数组中最小元素的所有数对数量。

算法思路
  1. 确定数组中的最小元素;
  2. 对数组进行排序,使其元素按升序排列;
  3. 遍历排序后的数组,对于当前元素 x,查找数组中第一个不小于 x + 最小元素的元素 y,y 之前的元素都可以与 x 构成满足条件的数对,计入统计量中。
示例代码
def count_pairs(arr):
    """
    统计绝对差不小于数组中最小元素的所有数对数量
    :param arr: 整数数组
    :return: 统计量
    """
    n = len(arr)
    min_element = min(arr)
    arr.sort()
    count = 0
    for i in range(n):
        j = i + 1
        while j < n and arr[j] - arr[i] < min_element:
            j += 1
        if j < n:
            count += n - j
    return count
时间复杂度

排序的时间复杂度为 O(nlogn),遍历的时间复杂度为 O(n),因此总的时间复杂度为 O(nlogn)。

参考资料

[1] LeetCode. (2019). Count Number of Pairs With Absolute Difference K. retrieve from https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/