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

时间:2015-02-16 10:31:45

标签: java algorithm collections min

我有一大堆整数,其值只能增长(我在计算东西)。

出于效率原因,我单独保留最大值,并在需要时更新:

// when increasing the i'th count
coll[i] += 1;
// check whether also to update the max:
if(coll[i] > max){
  max = coll[i];
}

什么是一个有效的算法来“跟随”集合的最小值?

通过高效我的意思是,尽可能少地迭代整个集合并保持较小的内存占用。 (后者实际上不如前者重要)

我正在使用Java:所以如果所述算法已经在JRE中,我欢迎参考。

1 个答案:

答案 0 :(得分:2)

保留每个值的计数哈希表,然后更新它,如果哈希表中没有更多的值等于min,则更新min。

// when increasing the i'th count
coll[i] += 1;
--hashTable[coll[i] - 1];
++hashTable[coll[i]];
// check whether also to update the max:
if(coll[i] > max){
  max = coll[i];
}
// check whether to update the min:
if(min == coll[i] - 1 && hashTable[coll[i] - 1] == 0){
  min = coll[i];
}

如果您能够负担内存(如果您的值足够小)或实际Hashtable,那么哈希表可以是一个简单的数组。

这只需要对集合进行初始迭代来构建哈希表。然后不再执行迭代。