我有一个大小为 [0, 8388608] 的大数组 A,其中包含“相对较小”的整数 A[i] = [0, 131072],我想找到每个 N=32 个元素中最常出现的元素。
什么会更快,
A、创建一个大小为131072的关联数组B,迭代32个元素,递增B[A[i]],然后迭代B,找到最大值,将B中所有元素重置为0,重复|A|/32次。
B. 每 32 个元素进行排序,找到 A[i] == A[i-1] 的最大范围(因此是最频繁的元素),重复 |A|/32 次。
(编辑)C.其他的东西。
对第一种方法的改进是可能的。不需要遍历B。并且它可以是大小为131072的数组
每次增加时B[A[i]]
,查看该单元格中的新值。然后,拥有一个全球highest_frequency_found_far
。它从零开始,但每次增量后,新值都应与该全局值进行比较。如果它更高,则全局被替换。
您还可以拥有全球value_that_was_associated_with_the_highest_count
for each block of 32 members of A ... {
size_t B [131072] = {0,0,...};
size_t highest_frequency_found_so_far = 0;
int value_associated_with_that = 0;
for(a : A) { // where A just means the current 32-element sub-block
const int new_frequency = ++B[a];
if (new_frequency > highest_frequency_found_so_far) {
highest_frequency_found_so_far = new_frequency;
value_associated_with_that = a;
}
}
// now, 'value_associated_with_that' is the most frequent element
// Thanks to @AkiSuihkonen for pointing out a really simple way to reset B each time.
// B is big, instead of zeroing each element explicitly, just do this loop to undo
// the ++B[a] from earlier:
for(a : A) { --B[a]; }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)