📜  给定数组中的第 K 个最小对和

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

给定数组中的第 K 个最小对和

给定一个大小为N的整数数组arr[]和一个整数K ,任务是找到给定数组的第 K 个最小对和

例子:

天真的方法:这是一种贪婪的方法。我们将获得所有可能对的总和并将它们存储在一个数组中。然后我们将按升序对该数组进行排序,第 K 个值是所需的答案。
时间复杂度: O (N 2 * log(N 2 ))
辅助空间: O(N 2 )

高效方法:这种方法的概念基于max-heap 。我们将实现一个大小为 K 的最大堆。请按照以下步骤操作:

  • 开始从i = 0i = N-2迭代数组。
    • 对于每个 ij = i+1迭代到j = N-1
    • 获取这个 (i, j) 对的总和并将其插入最大堆中
    • 如果堆已满,则将堆的顶部元素此总和进行比较
    • 如果顶部元素的值更大,则将其替换为新的 sum
  • 当迭代超过最大堆的最顶部元素时,是第K 个最小的对 sum

下面是上述方法的实现:

C++
#include 
using namespace std;
 
// Function to get the Kth smallest pair sum
int kthPairSum(vector& arr, int K)
{
    int n = arr.size();
 
    // Priority queue to implement max-heap
    priority_queue pq;
 
    // Loop to calculate all possible pair sum
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Variable to store the sum
            int temp = arr[i] + arr[j];
 
            // If the heap is full
            if (pq.size() == K) {
 
                // If the top element is greater
                if (pq.top() > temp) {
                    pq.pop();
                    pq.push(temp);
                }
            }
            else
                pq.push(temp);
        }
    }
 
    // Return the Kth smallest value
    return pq.top();
}
 
// Driver code
int main()
{
    vector arr = { 1, 5, 6, 3, 2 };
    int K = 3;
 
    cout << kthPairSum(arr, K);
    return 0;
}


Java
// Java code for the above approach
import java.util.*;
class GFG {
 
    // Function to get the Kth smallest pair sum
    static int kthPairSum(int[] arr, int K)
    {
        int n = arr.length;
 
        // Priority queue to implement max-heap
        // Creating empty priority queue
        PriorityQueue pq
            = new PriorityQueue(
                Collections.reverseOrder());
 
        // Loop to calculate all possible pair sum
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
 
                // Variable to store the sum
                int temp = arr[i] + arr[j];
 
                // If the heap is full
                if (pq.size() == K) {
 
                    // If the top element is greater
                    if (pq.peek() > temp) {
                        pq.poll();
                        pq.add(temp);
                    }
                }
                else
                    pq.add(temp);
            }
        }
 
        // Return the Kth smallest value
        return pq.peek();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 1, 5, 6, 3, 2 };
        int K = 3;
 
        System.out.println(kthPairSum(arr, K));
    }
}
 
// This code is contributed by Potta Lokesh


Python3
from queue import PriorityQueue
 
# Function to get the Kth smallest pair sum
def kthPairSum(arr, K):
    n = len(arr);
 
    # Priority queue to implement max-heap
    pq = PriorityQueue()
 
    # Loop to calculate all possible pair sum
    for i in range(n - 1):
        for j in range(i + 1, n):
 
            # Variable to store the sum
            temp = arr[i] + arr[j];
 
            # If the heap is full
            if (pq.qsize() == K):
 
                # If the top element is greater
                if (pq.queue[-1] > temp):
                    pq.get();
                    pq.put(temp);
            else:
                pq.put(temp);
 
    # Return the Kth smallest value
    return pq.queue[0];
 
# Driver code
arr = [ 1, 5, 6, 3, 2 ];
K = 3;
 
print(kthPairSum(arr, K));
 
# This code is contributed by saurabh_jaiswal.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to get the Kth smallest pair sum
    static int kthPairSum(int[] arr, int K)
    {
        int n = arr.Length;
 
        // Priority queue to implement max-heap
        // Creating empty priority queue
        List pq = new List();
 
        // Loop to calculate all possible pair sum
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
 
                // Variable to store the sum
                int temp = arr[i] + arr[j];
 
                // If the heap is full
                if (pq.Count  == K) {
 
                    // If the top element is greater
                    if (pq[0] > temp) {
                        pq.Remove(0);
                        pq.Add(temp);
                    }
                }
                else
                    pq.Add(temp);
                 
            }
        }
 
        // Return the Kth smallest value
        return pq[0]-1;
    }
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 5, 6, 3, 2 };
    int K = 3;
 
    Console.Write(kthPairSum(arr, K));
}
}
 
// This code is contributed by avijitmondal1998.


输出
5

时间复杂度: O(N 2 * logK)
辅助空间: O(K)