当前位置: 移动技术网 > IT编程>开发语言>Java > 面试题 16.10. 生存人数

面试题 16.10. 生存人数

2020年07月17日  | 移动技术网IT编程  | 我要评论

给定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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

package org.dai.io.cmd.command;

/**
 * 给定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
 * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 *
 */
public class Solution11 {

	public static void main(String[] args) {
		int[] birth = new int[] { 1900, 1901, 1950 };
		int[] death = new int[] { 1948, 1951, 2000 };
		Solution11 so3 = new Solution11();
		int rs = so3.maxAliveYear(birth, death);
		System.out.println(rs);

	}

	public int maxAliveYear(int[] birth, int[] death) {
		int[] years = new int[102];
		for (int i = 0; i < birth.length; i++) {
			int b = birth[i] - 1900;
			int d = death[i] - 1900;
			years[b]++;
			years[d + 1]--;
		}
		int year = 1900;
		int sum = 0;
		int max = 0;
		for (int i = 0; i < years.length; i++) {
			int c = years[i];
			if (c > 0) {
				sum = sum + c;
				if (sum > max) {
					year = i;
					max=sum;
				}
			} else if (c < 0) {
				sum = sum + c;
			}
		}

		return year + 1900;

	}
}

 

本文地址:https://blog.csdn.net/u012746134/article/details/107350816

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网