如何找到所有的有序对的整数,其总和的数组元素在于价值给定范围内有的、范围内、整数、数组

2023-09-11 03:19:44 作者:芳草鲜美

鉴于整数数组找到所有有序对元件中的,其总和在于在给定的范围内的阵列中的编号[A,B]

下面是一个为O​​(n ^ 2)解决方案相同的

 '''
计算阵列中的所有对这样的
一对的总和在于范围a和b
'''
高清countpairs(阵列,A,B):
    num_of_pairs = 0
    因为我在范围内(LEN(阵列)):
        对于j范围内的第(i + 1,LEN(阵列)):
            总=阵列[I] +阵列[J]。
            如果总> = a和总< = B:
                num_of_pairs + = 1
    返回num_of_pairs
 

我知道我的解决办法是不是最佳 什么是这样做一个更好的算法。

解决方案 排序(按照升序说)阵列。 对于每一个元素x数组中: 在考虑阵列片的 的元素。在 请这个数组切片[A - X]的二进制搜索,称之为Y0。如果没有找到准确的匹配,考虑到最匹配的大的比[A - X]。为Y0 输出都从Y0元素(x,y)的前锋,只要X + Y< = B

的时间复杂度是当然的输出敏感,但是这仍然是优于现有算法中:

  O(nlogn)+ O(K)
 
两数之和 给定一个整数数组,找出其中两个数相加等于目标值

,其中k是满足条件对的数目

请注意:如果你只需要的计数的对数,就可以做到这一点在 O(nlogn)。修改上面的算法,所以[B - X(或下一个更小的元素)也被搜索。通过这种方式,你可以指望'匹配'的每个元素在数O(LOGN)简单地从第一个和最后一场比赛的指标。然后,它总结了那些获得最终计数的只是一个问题。这样一来,最初的 O(nlogn)筛选工序是主要的。

Given an array of integers find the number of all ordered pairs of elements in the array whose sum lies in a given range [a,b]

Here is an O(n^2) solution for the same

'''
counts all pairs in array such that the 
sum of pair lies in the range a and b
'''
def countpairs(array, a, b):
    num_of_pairs = 0
    for i in range(len(array)):
        for j in range(i+1,len(array)):
            total = array[i] + array[j]
            if total >= a and total <= b:
                num_of_pairs += 1
    return num_of_pairs

I know my solution is not optimal What is a better algorithm for doing this.

解决方案

Sort the array (say in increasing order). For each element x in the array: Consider the array slice after the element. Do a binary search on this array slice for [a - x], call it y0. If no exact match is found, consider the closest match bigger than [a - x] as y0. Output all elements (x, y) from y0 forwards as long as x + y <= b

The time complexity is of course output-sensitive, but this is still superior to the existing algo:

O(nlogn) + O(k)

where k is the number of pairs that satisfy the condition.

Note: If you only need to count the number of pairs, you can do it in O(nlogn). Modify the above algorithm so [b - x] (or the next smaller element) is also searched for. This way, you can count the number of 'matches' each element has in O(logn) simply from the indices of the first and last match. Then it's just a question of summing those up to get the final count. This way, the initial O(nlogn) sorting step is dominant.