key
以下行为:对于所有密钥联合中存在的每个密钥,输出元组应包含每个列表中的“当前”值。 如果输入列表在该密钥上没有条目,则应从该列表中启动最新值(即,使用小于或等于当前密钥的最新密钥中的值)。 这里是一个完整而最小的例子: 给定两个列表:
(key, value_from_list1, value_from_list2, ..., value_from_listK)
A = [(1, a1), (2, a2), (10, a3)]
B = [(1, b1), (8, b2), (10, b3)]
Algorithm效率:将分类列表与丢失键的随身携带机制合并的最有效算法是什么?
我当前的解决方案是使用带有多个指针的清扫线算法(对于每个列表)来跟踪我通过键联合迭代的最新价值。如果我没记错的话,这将在o(n log(n))
中运行Edit2025-03-13
Pseudocode
I’根据thisPost中的用户Smylic的建议创建了伪代码。正如他所说:
C = [
(1, a1, b1), // At key 1, both lists provide values.
(2, a2, b1), // At key 2, list A updates to a2; list B still uses b1.
(8, a2, b2), // At key 8, list B updates to b2; list A remains at a2.
(10, a3, b3) // At key 10, both lists update.
]
如果有不同的键和
function mergeLists(lists):
k = number of lists
pointers = array of size k, all initialized to 0
lastValues = array of size k, initially set to None (or some default)
output = empty list
while true:
minKey = None
// Find the minimum key among the current pointers in all lists.
for i from 0 to k-1:
if pointers[i] < length(lists[i]):
currentKey = lists[i][pointers[i]].key
if minKey is None or currentKey < minKey:
minKey = currentKey
// If no minimum key was found, all lists are exhausted.
if minKey is None:
break
// Update lastValues for each list that has the current minKey
for i from 0 to k-1:
if pointers[i] < length(lists[i]) and lists[i][pointers[i]].key == minKey:
lastValues[i] = lists[i][pointers[i]].value
pointers[i] = pointers[i] + 1
// Append the merged tuple (minKey, lastValues[0], lastValues[1], ..., lastValues[k-1])
output.append( (minKey, lastValues[0], lastValues[1], ..., lastValues[k-1]) )
return output
n