合并k个排序数组时处理重复值
Handling duplicate values while merging k sorted arrays
我正在尝试将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)。插入之前,请检查其中是否存在元素。如果不存在,请将该元素插入列表和哈希表中。
但你可以做得更好。由于您正在合并已排序的数组,因此输出也将进行排序。因此,如果存在重复项,它们将在输出数组中放在一起。因此,在插入之前,请使用输出的最后一个值检查该值。
相关文章:
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 处理数组时make_unique和make_shared之间的差异
- 我如何处理数组的单个元素
- 如何在 c++ 预处理器宏中处理数组元素?
- 返回处理数组的INT功能
- 我可以使用模板作为多态处理数组的安全解决方案
- "corresponding elements"处理数组内容,我需要解释
- STL 是否包含处理数组的迭代器
- 多次C++处理数组元素
- 如何处理数组C++中的分段错误
- 处理数组
- 处理数组时出错 C++
- 在c++中处理数组的问题
- 在c++中处理数组
- 用c++在Arduino上处理数组
- 并行处理数组索引的最佳方式
- 可以用不同的大括号处理数组初始化的样式
- 在处理数组访问时可能会生成不一致的代码
- C/C++的压缩库能够处理数组中超过32位的元素
- 如何在引发异常时安全地处理数组指针