可以采用双重循环的方式,依次取出每个元素并与其他元素进行比较,统计交集的次数。将统计结果保存在一个关联数组中,键为元素的值,值为交集次数。最后遍历关联数组,找出值最大的键即可。

示例代码:

function getMaxIntersection($arr) {
    $count = count($arr);
    $result = array();
    for ($i = 0; $i < $count; $i++) {
        $temp = array();
        for ($j = 0; $j < $count; $j++) {
            if ($i == $j) {
                continue;
            }
            $intersection = array_intersect($arr[$i], $arr[$j]);
            $temp = array_merge($temp, $intersection);
        }
        foreach ($temp as $value) {
            if (!isset($result[$value])) {
                $result[$value] = 1;
            } else {
                $result[$value]++;
            }
        }
    }
    arsort($result);
    $keys = array_keys($result);
    return $keys[0];
}

$arr = array(
    array('a', 'b', 'c'),
    array('a', 'd', 'e'),
    array('a', 'b', 'e'),
    array('a', 'c', 'd')
);

echo getMaxIntersection($arr); // 输出: a
``
PHP 获取一维数组中元素箭交集次数最多的字

原文地址: https://www.cveoy.top/t/topic/eHtO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录