给出一个列表,列出他们的出生日期和结束年份(都在1900年至2017年之间),找出活着的人最多的年份。
<?php
class Person {
function __construct($birth, $death) {
$this->birthYear = $birth;
$this->deathYear = $death;
}
};
$people = [
new Person(1925, 1972),//47
new Person(1901, 1960),//59
new Person(1942, 1999),//57
new Person(1960, 2010),//50
new Person(1931, 2017),//86
new Person(1961, 1995),//34
new Person(1919, 1982),//63
];
$birth = array_column($people,"birthYear");
$death = array_column($people,"deathYear");
$START_YEAR = 1900;
$END_YEAR = 2017+1;
$people_alive = [];
$people = json_decode(json_encode($people),true);
foreach($people as $k=>$v){
$a = $v['birthYear'] - $START_YEAR;
$b = $v['deathYear'] - $START_YEAR +1;
$people_alive[]= $b-$a +1;
}
print_r($people_alive);
我试图将解决方案从python转换为PHP,但这不是我想要的。 python解决方案
Array
(
[0] => 49
[1] => 61
[2] => 59
[3] => 52
[4] => 88
[5] => 36
[6] => 65
)
我想要一年中大多数人还活着的一年。 我对如何创建此逻辑感到困惑。
答案 0 :(得分:0)
最简单的解决方案是遍历所有年份,并计算给定年份有多少人还活着。然后,找到人数最多的年份-那将是活着的人数最多的年份。请记住,此解决方案不是最佳解决方案,并且具有复杂性O(n)
:
<?php
class Person {
public function __construct($birth, $death) {
$this->birthYear = $birth;
$this->deathYear = $death;
}
};
$people = [
new Person(1925, 1972),//47
new Person(1901, 1960),//59
new Person(1942, 1999),//57
new Person(1960, 2010),//50
new Person(1931, 2017),//86
new Person(1961, 1995),//34
new Person(1919, 1982),//63
];
$start = 1900;
$end = 2017;
// create list of years in given time frame
$years = array_fill($start, $end - $start + 1, 0);
// iterate through all the people
foreach ($people as $person) {
for ($i = $person->birthYear; $i <= $person->deathYear; ++$i) {
$years[$i] += 1;
}
}
// the maximum number of people alive in one year
$max_count = max($years);
// the year with the most number of people alive
$max_year = array_search($max_count, $years);