在不使用php内置函数的情况下查找数组中的大多数出现元素

时间:2015-02-17 10:01:16

标签: php

如何在给定数组中找到最多的出现元素 数组可以是偶数或奇数 我已经找到了使用php内置函数的答案,但我想通过自定义函数来做到这一点。请帮忙......

3 个答案:

答案 0 :(得分:0)

    <?php

    $array = array(1,1,1,4,3,1,3);

    $count_special= array_count_values_special($array);//Counts the values in the array, returns associatve array
    $count= array_count_values($array); //PHP Built in functionCounts the values in the array, returns associatve array

    asort($count_special);
    asort($count);
    print_r($count_special);
    print_r($count);

    function array_count_values_special($array) {
        $ret_array = array();
        foreach($array as $value) {
            foreach($ret_array as $key2 => $value2) {
                if($key2 == $value) {
                    $ret_array[$key2]++;
                    continue 2;
                }
            }
            $ret_array[$value] = 1;
        }
        return $ret_array;
    }

享受:)

答案 1 :(得分:0)

我不确定你所指的是“可以是偶数还是奇数”,但这是你想要的功能吗?

我不知道在PHP数组中查找对象的运行时,如果它像Java hashmap那样工作,那么每次查找都会花费O(1)。

这个+通过你的数组的foreach循环将是总O(n)。我不认为内置的PHP函数可能比这更快,假设我在PHP关联数组的工作原理中是正确的。

public function mostOccuranceInArray($array)
    {
        // create associative array where key => object value => num of occurances
        $occurancesArray = array();
        $maxOccurances = - 1;
        $mostFrequentVal = NULL;

        foreach ($array as $val) {

            if (! $occurancesArray[$val]) { // if we have not added this value yet
                $occurancesArray[$val] = 0;
            } else {
                $occurancesArray[$val] ++; // increment the number of occurances

                if ($occurancesArray[$val] > $maxOccurances) {
                    $maxOccurances = $occurancesArray[$val];
                    $mostFrequentVal = $val;
                }
            }
        }

        return $val;
    }

答案 2 :(得分:0)

我实现了一个返回最多值的数组的函数:

var_dump(mostOccurringInArray(array(1,1,1,4,3,1,3,4,3,4,4))); 
// array(2) { [4]=> int(4) [1]=> int(4) }
var_dump(mostOccurringInArray(array(1,1,1,4,3,1,3,4,3))); 
// array(1) { [1]=> int(4) }

function mostOccurringInArray($array) {
    $occurrences = array();
    foreach($array as $v) 
        !array_key_exists($v, $occurrences) ? $occurrences[$v] = 1 : $occurrences[$v]++;    
    asort($occurrences); 
    $max = end($occurrences); 
    return array_filter($occurrences, function($value) use(&$max) { return $value == $max; });
}

如果您只想返回一个值:

function mostOccurringInArray($array) {
    $occurrences = array();
    foreach($array as $v) 
        !array_key_exists($v, $occurrences) ? $occurrences[$v] = 1 : $occurrences[$v]++;    
    asort($occurrences); 
    end($occurrences); 
    return key($occurrences);
}