📌  相关文章
📜  用于在两个数组中查找具有最小和最小的 k 对的 Python3 程序

📅  最后修改于: 2022-05-13 01:55:03.516000             🧑  作者: Mango

用于在两个数组中查找具有最小和最小的 k 对的 Python3 程序

给定两个按升序排序的整数数组 arr1[] 和 arr2[] 以及一个整数 k。找到k个和最小的对,使得一对中的一个元素属于arr1[],另一个元素属于arr2[]
例子:

Input :  arr1[] = {1, 7, 11}
         arr2[] = {2, 4, 6}
         k = 3
Output : [1, 2],
         [1, 4],
         [1, 6]
Explanation: The first 3 pairs are returned 
from the sequence [1, 2], [1, 4], [1, 6], 
[7, 2], [7, 4], [11, 2], [7, 6], [11, 4], 
[11, 6]

方法1(简单)

  1. 找到所有对并存储它们的总和。此步骤的时间复杂度为 O(n1 * n2),其中 n1 和 n2 是输入数组的大小。
  2. 然后根据总和对对进行排序。这一步的时间复杂度是 O(n1 * n2 * log (n1 * n2))

总体时间复杂度:O(n1 * n2 * log (n1 * n2))
方法2(高效):
我们从最小和对开始,一一找到k个最小和对。这个想法是跟踪 arr2[] 的所有元素,这些元素已经为每个元素 arr1[i1] 考虑过,以便在迭代中我们只考虑下一个元素。为此,我们使用索引数组 index2[] 来跟踪另一个数组中下一个元素的索引。它只是意味着在每次迭代中将第二个数组的哪个元素与第一个数组的元素相加。我们在索引数组中为形成下一个最小值对的元素增加值。

Python3
# Python3 program to prints first k pairs with least sum from two
# arrays.
 
import sys
# Function to find k pairs with least sum such
# that one element of a pair is from arr1[] and
# other element is from arr2[]
def kSmallestPair(arr1, n1, arr2, n2, k):
    if (k > n1*n2):
        print("k pairs don't exist")
        return
 
    # Stores current index in arr2[] for
    # every element of arr1[]. Initially
    # all values are considered 0.
    # Here current index is the index before
    # which all elements are considered as
    # part of output.
    index2 = [0 for i in range(n1)]
 
    while (k > 0):
        # Initialize current pair sum as infinite
        min_sum = sys.maxsize
        min_index = 0
 
        # To pick next pair, traverse for all elements
        # of arr1[], for every element, find corresponding
        # current element in arr2[] and pick minimum of
        # all formed pairs.
        for i1 in range(0,n1,1):
            # Check if current element of arr1[] plus
            # element of array2 to be used gives minimum
            # sum
            if (index2[i1] < n2 and arr1[i1] + arr2[index2[i1]] < min_sum):
                # Update index that gives minimum
                min_index = i1
 
                # update minimum sum
                min_sum = arr1[i1] + arr2[index2[i1]]
         
        print("(",arr1[min_index],",",arr2[index2[min_index]],")",end = " ")
 
        index2[min_index] += 1
 
        k -= 1
 
# Driver code
if __name__ == '__main__':
    arr1 = [1, 3, 11]
    n1 = len(arr1)
 
    arr2 = [2, 4, 8]
    n2 = len(arr2)
 
    k = 4
    kSmallestPair( arr1, n1, arr2, n2, k)
 
# This code is contributed by
# Shashank_Sharma


输出
(1, 2) (1, 4) (3, 2) (3, 4) 

时间复杂度: O(k*n1)
有关更多详细信息,请参阅有关在两个数组中查找具有最小和的 k 对的完整文章!