📅  最后修改于: 2023-12-03 15:06:38.551000             🧑  作者: Mango
给定一个整数数组,计算其中绝对差不小于数组中最小元素的所有数对数量。
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/