Find the most common number
EASY
Given an input string with numbers separated by a single space.
Find the most common number in this line.
Solution
<?php
$line = trim(fgets(STDIN));
$nums = explode(' ', $line);
$nums2Freq = [];
$currentMaxFreq = 1;
$currentMaxNum = $nums[0];
foreach ($nums as $num) {
if (!isset($nums2Freq[$num])) {
$nums2Freq[$num]=1;
} else {
$nums2Freq[$num]++;
}
if ($nums2Freq[$num] > $currentMaxFreq) {
$currentMaxFreq = $nums2Freq[$num];
$currentMaxNum = $num;
}
}
echo $currentMaxNum;
Tests
Test #1 |
Loading...
|
Test #2 |
Loading...
|
Test #3 |
Loading...
|
Test #4 |
Loading...
|
Test #5 |
Loading...
|
Test #6 |
Loading...
|