简体   繁体   English

如何使用时间复杂度优于O(n ^ 2)的STL向量和STL算法进行左连接?

[英]How to do a left join with STL vector and STL algorithms with time complexity better than O(n^2)?

I have 2 vectors, which contain, let's say Person (name, surname, etc) objects. 我有2个向量,包含,让我们说Person(姓名,姓氏等)对象。 I want to take one of the vectors (let's name it "large") then for each element in this vector find corresponding element in second one ("small") and merge some data from "small" vector element to the "large" vector element. 我想取一个向量(让它命名为“大”)然后对于这个向量中的每个元素在第二个中找到对应的元素(“小”)并将一些数据从“小”向量元素合并到“大”向量元件。 This operation is very similar to left join in SQL terms, but with additional merge of the data. 此操作与SQL术语中的左连接非常相似,但具有额外的数据合并。 The easiest way is to make 2 cycles, but that will lead to O(n^2) time complexity. 最简单的方法是进行2个循环,但这将导致O(n ^ 2)时间复杂度。 Can I do better with STL algorithms? 我可以用STL算法做得更好吗?

如果小向量进行排序 ,则可以通过扫描大向量获取合并部分的O(n log n),并使用binary_search查找小向量中的元素。

Yes! 是! You can do it in O(nlogn) time complexity. 您可以在O(nlogn)时间复杂度中执行此操作。 Sort the second vector, which takes O(nlogn) time. 对第二个向量进行排序,需要O(nlogn)时间。 for each element in first vector, find corresponding element in second one using binary search (STL has binary_search algorithm) and merge data to the element in first vector. 对于第一个向量中的每个元素,使用二分搜索(STL具有binary_search算法)在第二个元素中找到对应的元素,并将数据合并到第一个向量中的元素。 for each element in first vector, we are spending O(logn) time. 对于第一个向量中的每个元素,我们花费O(logn)时间。 So the running time complexity of this approach is O(nlogn). 因此,这种方法的运行时间复杂度为O(nlogn)。

If your lists don't change often, you can sort both lists and then do the merge in linear time by simply walking both lists. 如果您的列表不经常更改,您可以对两个列表进行排序,然后通过简单地遍历两个列表以线性时间进行合并。

If your lists are changing all the time, you're probably better off making the "small" container sorted, such as map or set . 如果您的列表一直在变化,那么您可能最好将“小”容器排序,例如mapset In that case just use find on the set for each item in the big list you want to join. 在这种情况下,只需对要加入的大列表中的每个项目使用find

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM