合并k个排序数组时处理重复值

Handling duplicate values while merging k sorted arrays

本文关键字:处理 数组 排序 合并      更新时间:2023-10-16

我正在尝试将k个排序的结构数组合并为一个数组。我知道使用最小堆合并数组的算法。我使用C++中的priority_queue来实现堆。我的代码如下所示。

struct Num {
    int key;
    int val;
}
// Struct used in priority queue.
struct HeapNode
{
    Num num;              // Holds one element.
    int vecNum;           //Array number from which the element is fetched.
    int vecSize;          // Holds the size of the array.
    int next;             // Holds the index of the next element to fetch.
};
// Struct used to compare nodes in a priority queue.
struct CompareHeapNode  
{  
    bool operator()(const HeapNode& x, const HeapNode& y)  
    {  
        return (x.num.key < y.num.key) || ( (x.num.key == y.num.key)&&(x.num.val < y.num.val) ); 
    } 
}; 
vector<vector<Num>> v;
priority_queue< HeapNode, vector<HeapNode>, CompareHeapNode> p_queue;
//Insert the first element of the individual arrays into the heap.
while(!p_queue.empty())  
{  
    Num x = p_queue.top();
    cout << x.num.key << ' ' << x.num.val << 'n';
    p_queue.pop();
    if(x.next != x.vecSize) {
        HeapNode hq = {v[x.vecNum][x.next], x.vecNum, x.vecSize, ++x.next};
        p_queue.push(hq);
    }  
}

让我们考虑3个排序的数组,如下所示。

Array1:             Array2:         Array3:
0 1                 0 10            0 0
1 2                 2 22            1 2
2 4                 3 46            2 819
3 7                 4 71            3 7321

现在的问题是,数组中可能存在一些常见的元素,如上所示。因此,在合并数组时,排序后的数组中会出现重复的值。有什么方法可以处理重复的钥匙吗?

所以你的问题是,有没有一种方法可以检查你插入到列表中的值是否已经在列表中。只要你能检查一下。

一种解决方案是使用哈希表(unordered_set)。插入之前,请检查其中是否存在元素。如果不存在,请将该元素插入列表和哈希表中。

但你可以做得更好。由于您正在合并已排序的数组,因此输出也将进行排序。因此,如果存在重复项,它们将在输出数组中放在一起。因此,在插入之前,请使用输出的最后一个值检查该值。