代码之家  ›  专栏  ›  技术社区  ›  Bruce

在php中找到最大频率元素的最快方法

php
  •  1
  • Bruce  · 技术社区  · 15 年前

    我有1274151573123794这样的身份证…(范围未知)。在php中找到最大频率id的最快方法是什么?

    $array_ids = array()
    
    4 回复  |  直到 14 年前
        1
  •  6
  •   user187291    15 年前
    $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";
    
        2
  •  7
  •   user187291    14 年前
    // 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) .

        3
  •  2
  •   acm    15 年前

    解决同频率多个元件的问题:

    $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 combo快一点……

        4
  •  0
  •   Salil    15 年前

    尝试 max

    $max = max($array_ids);
    
    推荐文章