Quickest way to find the max frequency element in PHP
I have an array of ids like 127415157,31323794... (range not known). What is the quickest way to find the max frequen开发者_如何学编程cy ID in PHP?
$array_ids = array()
// 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);
The suggestion of using array_search()
combined with max()
may be faster than this, however, since it doesn't need to completely sort the array, and thus will run in O(n)
time instead of O(n log n)
.
$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";
Addressing the issue of multiple elements with same frequency:
$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 ";
this will ouput
most frequent value is/are 5,3
also, it's a little faster than using array_search and max combo...
Try max
$max = max($array_ids);
精彩评论