Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
function findMajorityElement(array $inputArray = null): string|int|null
{
//$countValues = array_count_values($inputArray);
$countValues = array_reduce (
$inputArray,
function($acc, $el) {
if (is_null($el)) $el = 'null';
if (!isset($acc[$el])) $acc[$el] = 1;
else $acc[$el] ++;
return $acc;
},
[]
);
var_dump($countValues);
arsort($countValues, SORT_REGULAR);
$expectedMajorityElement = reset($countValues);
if (count($inputArray) / 2 > $expectedMajorityElement) {
return "Current array doesn't have a majority element.";
}
return key($countValues);
}
/*
Не могу понять, как сделать проверку, если введённый массив [null,null,null и т.д] и вернуть null.
php unit: "Expected result should be null" => [null, [null, null, null]],
*/
print_r(findMajorityElement([null, null, '']));