问题描述
我想对向量中的项目重新排序,使用另一个向量来指定顺序:
I'd like to reorder the items in a vector, using another vector to specify the order:
以下是需要复制向量的低效实现:
The following is an inefficient implementation that requires copying the vector:
有没有更有效的方法,例如,使用 swap()?
Is there a more efficient way, for example, that uses swap()?
推荐答案
该算法基于 chmike 的,但重新排序索引的向量是 const
.这个功能都同意他的11![0..10] 的排列.复杂度为 O(N^2),取 N 作为输入的大小,或者更准确地说,最大的大小 轨道.
This algorithm is based on chmike's, but the vector of reorder indices is const
. This function agrees with his for all 11! permutations of [0..10]. The complexity is O(N^2), taking N as the size of the input, or more precisely, the size of the largest orbit.
有关修改输入的优化 O(N) 解决方案,请参见下文.
See below for an optimized O(N) solution which modifies the input.
这是一个 STL 风格的版本,我投入了更多的精力.它快了大约 47%(也就是说,几乎是 [0..10] 的两倍!)因为它尽可能早地完成所有交换然后返回.重新排序向量由许多轨道组成,每个轨道在到达其第一个成员时重新排序.当最后几个元素不包含轨道时,速度会更快.
Here's an STL style version which I put a bit more effort into. It's about 47% faster (that is, almost twice as fast over [0..10]!) because it does all the swaps as early as possible and then returns. The reorder vector consists of a number of orbits, and each orbit is reordered upon reaching its first member. It's faster when the last few elements do not contain an orbit.
最后,为了一劳永逸地回答这个问题,一个会破坏重新排序向量的变体(用 -1 填充它).对于 [0..10] 的排列,它比之前的版本快了大约 16%.因为覆盖输入可以实现动态规划,所以它是 O(N),对于某些序列较长的情况,渐近更快.
And finally, just to answer the question once and for all, a variant which does destroy the reorder vector (filling it with -1's). For permutations of [0..10], It's about 16% faster than the preceding version. Because overwriting the input enables dynamic programming, it is O(N), asymptotically faster for some cases with longer sequences.
这篇关于使用索引向量重新排序向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!