在這本書中「的算法設計手冊」,由Skiena,計算一組的模式(最常見的元素),據說有一個Ω(ñ日誌ñ)下限(這讓我爲難) ,但也(正確地我猜)沒有更快的最壞情況算法存在計算模式。我只是通過下界是Ω(ñ日誌ñ)不解。以線性時間計算一個集合的模式(最頻繁的元素)?
的書頁但可以肯定,這可能在某些情況下以線性時間(最好的情況下),例如計算通過下面的Java代碼(在字符串中找到最常見的字符),「技巧」是使用散列表來計算出現次數。這似乎很明顯。
所以,我是什麼,我對問題的理解缺失?
編輯:(神祕解決)作爲StriplingWarrior指出,下界持有,如果只使用比較,即沒有內存索引,也看到:http://en.wikipedia.org/wiki/Element_distinctness_problem
// Linear time
char computeMode(String input) {
// initialize currentMode to first char
char[] chars = input.toCharArray();
char currentMode = chars[0];
int currentModeCount = 0;
HashMap<Character, Integer> counts = new HashMap<Character, Integer>();
for(char character : chars) {
int count = putget(counts, character); // occurences so far
// test whether character should be the new currentMode
if(count > currentModeCount) {
currentMode = character;
currentModeCount = count; // also save the count
}
}
return currentMode;
}
// Constant time
int putget(HashMap<Character, Integer> map, char character) {
if(!map.containsKey(character)) {
// if character not seen before, initialize to zero
map.put(character, 0);
}
// increment
int newValue = map.get(character) + 1;
map.put(character, newValue);
return newValue;
}
似乎沒有在勘誤列表中提到: http://www.cs.sunysb.edu/~skiena/algorist/book/errata – 2010-11-12 20:08:58
無法讀取頁面。一些古怪的信息,顯然是丹麥人。 – 2010-11-12 20:17:04
將google.dk更改爲google.com,即可使用。 – StriplingWarrior 2010-11-12 20:20:49