【程序员面试金典】16.10. 生存人数(数组哈希)

1.题目

给定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]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/living-people-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.题解

直接就数组记录人数,最后遍历选择最大的那一年。

class Solution {
public:
    int maxAliveYear(vector<int>& birth, vector<int>& death) {
        // 获取出生中的最小年份
        int min_year = *min_element(birth.begin(), birth.end());
        // 获取死亡中的最大年份
        int max_year = *max_element(death.begin(), death.end());
        // 创建一个年份数组,从最小年份~最大年份
        vector<int> human(max_year - min_year + 1, 0);
        for (int i = 0; i < birth.size(); ++i) {
            int start = birth[i], end = death[i];
            while (start <= end) {
                ++human[start - min_year];
                ++start;
            }
        }
        // 寻找人数最多的年份
        int cnt = human[0], offset = 0;
        for (int i = 0; i < human.size(); ++i) {
            if (human[i] > cnt) {
                cnt = human[i];
                offset = i;
            }
        }
        return min_year + offset;
    }
};


树状数组:

const int hi = 102;

int lowbit(int x) {
    return x & (-x);
}

class Solution {
    vector<int> live;
    
    void update(int idx, int delta) {
        for (; idx < hi; idx += lowbit(idx))
            live[idx] += delta;
    }
    
    int query(int idx) {
        int ans = 0;
        for (; idx > 0; idx -= lowbit(idx))
            ans += live[idx];
        return ans;
    }
public:
    int maxAliveYear(vector<int>& birth, vector<int>& death) {
        live = vector<int>(hi);
        for (int i = 0; i < birth.size(); ++i) {
            update(birth[i] - 1899, 1);
            update(death[i] - 1898, -1);
        }
        int ans = -1, best = 0;
        for (int i = 1; i <= 101; ++i) {
            int year = query(i);
            if (year > best) {
                best = year;
                ans = i + 1899;
            }
        }
        return ans;
    }
};

链接:https://leetcode-cn.com/problems/living-people-lcci/solution/shu-zhuang-shu-zu-by-lucifer1004/
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值