[英]Quickest way to find the max frequency element in PHP
I have an array of ids like 127415157,31323794... (range not known). 我有一个ID数组,例如127415157,31323794 ...(范围未知)。 What is the quickest way to find the max frequency ID in PHP?
在PHP中找到最大频率ID的最快方法是什么?
$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)
. 但是,将
array_search()
与max()
array_search()
结合使用的建议可能比此方法更快,因为它不需要对数组进行完全排序,因此将在O(n)
时间而不是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
最频繁的值是/ 5,3
also, it's a little faster than using array_search and max combo... 而且,它比使用array_search和max组合要快一点。
尝试最大
$max = max($array_ids);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.