zoukankan      html  css  js  c++  java
  • 程序员面试金典-面试题 16.10. 生存人数

    题目:

    给定N个人的出生年份和死亡年份,第i个人的出生年份为birth[i],死亡年份为death[i],实现一个方法以计算生存人数最多的年份。

    你可以假设所有人都出生于1900年至2000年(含1900和2000)之间。如果一个人在某一年的任意时期都处于生存状态,那么他们应该被纳入那一年的统计中。例如,生于1908年、死于1909年的人应当被列入1908年和1909年的计数。

    如果有多个年份生存人数相同且均为最大值,输出其中最小的年份。

    示例:

    输入:
    birth = {1900, 1901, 1950}
    death = {1948, 1951, 2000}
    输出: 1901
    提示:

    0 < birth.length == death.length <= 10000
    birth[i] <= death[i]

    分析:

    开辟一个数组用来存储每一年出生的人数和死亡的人数,出生+1,死亡-1,统计生存人数最大值时从头开始遍历数组,将每一年的数字累加起来就是当年的存活人数,不断更新最大值即可。

    程序:

    class Solution {
        public int maxAliveYear(int[] birth, int[] death) {
            int[] arr = new int[102];
            for(int i = 0; i < birth.length; ++i){
                arr[birth[i] - 1900]++;
                arr[death[i] - 1900 + 1]--;
            }
            int cur = 0, max = 0, res = 0;
            for(int i = 0; i < arr.length; ++i){
                cur += arr[i];
                if(cur > max){
                    max = cur;
                    res = i + 1900;
                }
            }
            return res;
        }
    }
  • 相关阅读:
    MySQL优化实例
    MySQL优化步骤和my.cnf优化配置
    linux高负载下mysql数据库彻底优化
    MySQL配置文件my.cnf详解
    CentOS Linux下MySQL 5.1.x的安装、优化和安全配置
    Apache 配置文件详解
    [LeetCode] Number of Boomerangs
    [LeetCode] Binary Watch
    [LeetCode] Reverse Linked List
    [LeetCode] Maximum Product of Three Numbers
  • 原文地址:https://www.cnblogs.com/silentteller/p/12497439.html
Copyright © 2011-2022 走看看