寻找不同值的整数对(Finding number of pairs of integers differing by a value)

编程入门 行业动态 更新时间:2024-10-11 23:27:27
寻找不同值的整数对(Finding number of pairs of integers differing by a value)

如果我们有一个整数数组,那么除了O(n ^ 2)之外,是否还有其他有效方法可以用来找出相差给定值的整数对数? 例如,对于数组4,2,6,7,相差2的整数对数是2 {(2,4),(4,6)}。 谢谢。

If we have an array of integers, then is there any efficient way other than O(n^2) by which one can find the number of pairs of integers which differ by a given value? E.g for the array 4,2,6,7 the number of pairs of integers differing by 2 is 2 {(2,4),(4,6)}. Thanks.

最满意答案

从列表中创建一个集合。 创建另一个集合,其中所有元素都由增量增加。 相交两组。 这些是你的配对的上限值。

在Python中:

>>> s = [4,2,6,7] >>> d = 2 >>> s0 = set(s) >>> sd = set(x+d for x in s0) >>> set((x-d, x) for x in (s0 & sd)) set([(2, 4), (4, 6)])

创建集合是O(n)。 相交的集合也是O(n),所以这是一个线性时间算法。

Create a set from your list. Create another set which has all the elements incremented by the delta. Intersect the two sets. These are the upper values of your pairs.

In Python:

>>> s = [4,2,6,7] >>> d = 2 >>> s0 = set(s) >>> sd = set(x+d for x in s0) >>> set((x-d, x) for x in (s0 & sd)) set([(2, 4), (4, 6)])

Creating the sets is O(n). Intersecting the sets is also O(n), so this is a linear-time algorithm.

更多推荐

本文发布于:2023-07-27 02:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1284008.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   Finding   number   differing   integers

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!