我希望优化一个当前时间复杂度为O(n2)的相当简单的算法。我有一份记录文件,其中每个记录需要与同一文件中的所有其他记录进行比较。如果两者是“相同”的(比较函数相当复杂),则输出匹配的记录。请注意,可能会有几个记录彼此匹配,没有顺序之分 - 只有匹配的真假。
伪代码:
For (outRec in sourceFile) {
Get new filePointer for targetFile //starting from the top of the file for inner loop
For (inRec in targetFile) {
if (compare(outRec, inRec) == TRUE ) {
write outRec
write inRec
}
increment some counters
}
increment some other counters
}
数据没有排序,也没有任何预处理方式可以对数据进行排序。
有什么想法可以使其复杂度低于O(n^2)?我考虑在代码中应用MapReduce模式,将外部和内部循环分开,并可能使用链式Map函数。我相当确定已经在Hadoop上解决了代码问题,但我想在编码之前检查替代方案。
欢迎提出建议!
添加:记录类型。基本上,我需要匹配名称/字符串。匹配类型如下例所示。
1,Joe Smith,Daniel Foster<br>
2,Nate Johnson,Drew Logan<br>
3,Nate Johnson, Jack Crank<br>
4,Joey Smyth,Daniel Jack Foster<br>
5,Joe Morgan Smith,Daniel Foster<br>
<br>
Expected output:
Records 1,4,5 form a match set
End of output
新增:这些文件将非常大。最大的文件预计将包含约2亿条记录。
O(n*n)
改为O(n*log(n))
。 - Bart Kiers