📜  使用优先队列的未排序数组中的第 K 个最小元素

📅  最后修改于: 2021-10-28 01:49:28             🧑  作者: Mango

给定一个由N 个整数和一个整数K组成的数组arr[] ,任务是使用 Priority Queue 找到数组中的K最小元素。

例子:

做法:思路是利用Java的PriorityQueue Collection或者priority_queue STL库来实现Max_Heap ,找到第K最小的数组元素。请按照以下步骤解决问题:

  1. 使用 priority_queue 实现最大堆
  2. 将前K 个数组元素推入priority_queue
  3. 从那以后,每次插入数组元素后,弹出priority_queue 顶部的元素。
  4. 完成数组遍历后,打印优先级队列顶部的元素作为所需答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find kth smallest array element
void kthSmallest(vector& v, int N, int K)
{
    // Implement Max Heap using
    // a Priority Queue
    priority_queue heap1;
 
    for (int i = 0; i < N; ++i) {
 
        // Insert elements into
        // the priority queue
        heap1.push(v[i]);
 
        // If size of the priority
        // queue exceeds k
        if (heap1.size() > K) {
            heap1.pop();
        }
    }
 
    // Print the k-th smallest element
    cout << heap1.top() << endl;
}
 
// Driver code
int main()
{
    // Given array
    vector vec = { 5, 20, 10, 7, 1 };
 
    // Size of array
    int N = vec.size();
 
    // Given K
    int K = 2;
 
    // Function Call
    kthSmallest(vec, N, K % N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class CustomComparator implements Comparator {
 
    @Override
    public int compare(Integer number1, Integer number2) {
        int value =  number1.compareTo(number2);
       
        // elements are sorted in reverse order
        if (value > 0) {
            return -1;
        }
        else if (value < 0) {
            return 1;
        }
        else {
            return 0;
        }
    }
}
class GFG{
 
// Function to find kth smallest array element
static void kthSmallest(int []v, int N, int K)
{
    // Implement Max Heap using
    // a Priority Queue
    PriorityQueue heap1 = new PriorityQueue(new CustomComparator());
 
    for (int i = 0; i < N; ++i) {
 
        // Insert elements into
        // the priority queue
        heap1.add(v[i]);
 
        // If size of the priority
        // queue exceeds k
        if (heap1.size() > K) {
            heap1.remove();
        }
    }
 
    // Print the k-th smallest element
    System.out.print(heap1.peek() +"\n");
}
 
// Driver code
public static void main(String[] args)
{
    // Given array
    int []vec = { 5, 20, 10, 7, 1 };
 
    // Size of array
    int N = vec.length;
 
    // Given K
    int K = 2;
 
    // Function Call
    kthSmallest(vec, N, K % N);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
 
# Function to find kth smallest array element
def kthSmallest(v, N, K):
     
    # Implement Max Heap using
    # a Priority Queue
    heap1 = []
  
    for i in range(N):
         
        # Insert elements into
        # the priority queue
        heap1.append(v[i])
  
        # If size of the priority
        # queue exceeds k
        if (len(heap1) > K):
            heap1.sort()
            heap1.reverse()
            del heap1[0]
  
    # Print the k-th smallest element
    heap1.sort()
    heap1.reverse()
    print(heap1[0])
 
# Driver code
 
# Given array
vec = [ 5, 20, 10, 7, 1 ]
 
# Size of array
N = len(vec)
 
# Given K
K = 2
 
# Function Call
kthSmallest(vec, N, K % N)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
// Function to find kth smallest array element
static void kthSmallest(int []v, int N, int K)
{
   
    // Implement Max Heap using
    // a Priority Queue
    List heap1 = new List();
    for (int i = 0; i < N; ++i) {
 
        // Insert elements into
        // the priority queue
        heap1.Add(v[i]);
 
        // If size of the priority
        // queue exceeds k
        if (heap1.Count > K) {
            heap1.Sort();
            heap1.Reverse();
            heap1.RemoveAt(0);
        }
    }
    heap1.Sort();
            heap1.Reverse();
 
    // Print the k-th smallest element
    Console.WriteLine(heap1[0]);
}
 
// Driver code
public static void Main(String[] args)
{
   
    // Given array
    int []vec = { 5, 20, 10, 7, 1 };
 
    // Size of array
    int N = vec.Length;
 
    // Given K
    int K = 2;
 
    // Function Call
    kthSmallest(vec, N, K % N);
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:
5

时间复杂度: O(N LogK)
辅助空间: O(K),因为优先级队列随时保持在最大 k 个元素上。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程