我有一系列ID,如127415157,31323794 ...(范围未知).在PHP中找到最大频率ID的最快方法是什么?
$array_ids = array()
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)
然而,使用array_search()组合的建议max()可能比这更快,因为它不需要对数组进行完全排序,因此将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";
Run Code Online (Sandbox Code Playgroud)