我有一個像127415157,31323794 ......(範圍未知)的ID數組。在PHP中找到最大頻率ID的最快方法是什麼?在PHP中找到最大頻率元素的最快方法
$array_ids = array()
我有一個像127415157,31323794 ......(範圍未知)的ID數組。在PHP中找到最大頻率ID的最快方法是什麼?在PHP中找到最大頻率元素的最快方法
$array_ids = array()
$a = array(1, 2, 3, 4, 3, 3, 4, 4, 1, 3);
$r = array_count_values($a);
$k = array_search(max($r), $r);
echo "most frequent value is $k";
// Gives us an associative array of id=>count mappings,
$counts = array_count_values($array_ids);
// and sorts it from largest to smallest count
arsort($counts);
// Gets the first key after sorting, which is the id with the largest count
$max_freq_id = key($counts);
使用array_search()
與max()
組合可以比這更快,但是,因爲它並不需要完全排序陣列的建議,並且因此將運行在O(n)
時間而不是O(n log n)
。
沒錯,忘了PHP的排序是在原地進行的。固定。 – Amber 2010-05-05 09:59:41
解決同頻多個元素的問題:
$values = array(1, 1, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6);
$freq = array_count_values($values);
arsort($freq);
$max = $val = key($freq);
while(next($freq) && current($freq) == $freq[$max]){
$val .= ','.key($freq);
}
echo " most frequent value is/are $val ";
這將輸出中
衆數/被5,3
也,它比使用array_search和max組合更快一點...
...歐拉項目? – medopal 2010-05-05 09:45:24
@medopal:不,但我GOOGLE了它,它看起來很有趣..可能會嘗試一下:) – Bruce 2010-05-05 09:48:21