algorithm - 在 4 个列表中查找一式三份

标签 algorithm search

我试图在给定 4 个 N 字符串数组的情况下,在 O(N*log(N)) 时间内找到一个字符串,该字符串对于至少 3 个数组是通用的,如果它存在,则返回按字典顺序排列的第一个字符串.

我尝试的是创建一个大小为 4*N 的数组,并从 4 个数组中添加项目,同时删除重复项。然后我对大数组进行了快速排序,以找到第一个最终的三次重复。

有人知道更好的解决方案吗?

最佳答案

您可以在 O(n log n) 中执行此操作,并具有恒定的额外空间。这是一个标准 k-way merge problem , 在对各个列表进行排序之后。如果单个列表可能包含重复项,则您需要在排序期间删除重复项。

因此,假设您有 list1list2list3list4:

Sort the individual lists, removing duplicates
Create a priority queue (min-heap) of length 4
Add the first item from each list to the heap
last-key = ""
last-key-count = 0
while not done
    remove the smallest item from the min-heap
    add to the heap the next item from the list that contained the item you just removed.
    if the item matches last-key
        increment last-key-count
        if last-key-count == 3 then
            output last-key
            exit done
        else
            last-key-count = 1
            last-key = item key
end while
// if you get here, there was no triplicate item

另一种方法是将所有列表组合成一个列表,然后对其进行排序。然后您可以按顺序浏览它以找到第一个一式三份。同样,如果单个列表可能包含重复项,则应在合并列表之前将其删除。

combined = list1.concat(list2.concat(list3.concat(list4)))
last-key = ""
last-key-count = 0
for i = 0 to combined.length-1
    if combined[i] == last-key
        last-key-count++
        if last-key-count == 3
            exit done
        else
            last-key = combined[i]
            last-key-count = 1
end for
// if you get here, no triplicate was found

关于algorithm - 在 4 个列表中查找一式三份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39735625/

相关文章:

java - 遵循只能增加的值集合中的最小值

java - 不使用 % 或任何 java 内置方法(数学),如何进行模幂运算?

android如何在arraylist中找到相似的字符串

azure - 长时间运行的 Azure 索引器引发 "Operation was cancelled"异常

JavaScript:在一行中搜索字符串,如果找到字符串则删除行

html - 如何添加功能 Bootstrap 搜索栏

python - 提取匹配字符串的最快方法

java - 如何在 java 中生成 0x00000000FFFFFFFF 长掩码?

arrays - 对于数组中的每个数字,找到其左侧第一个较小的数字

javascript - 字符串的 indexOf 方法如何在 JavaScript 中工作