@@ -24,6 +24,14 @@ death = {1948, 1951, 2000}
24
24
25
25
<!-- 这里可写通用的实现逻辑 -->
26
26
27
+ 不在乎某个区间,而是某一年的最多存活人数。
28
+
29
+ 可以使用哈希表来统计每年的存活人数,当 ` birth[i] >= year && year <= death[i] ` ,该年份的存活人数加一。
30
+
31
+ > 只有 ` birth ` 和 ` death ` 当中的出现过的年份才是有效年份,或者说,可能成为返回值的年份。
32
+
33
+ 题目当中已说明年份范围是 ` 1900 ~ 2000 ` ,对此也可以使用数组进行计数(` year - 1900 ` )。
34
+
27
35
<!-- tabs:start -->
28
36
29
37
### ** Python3**
@@ -77,6 +85,66 @@ class Solution {
77
85
}
78
86
```
79
87
88
+ ### ** TypeScript**
89
+
90
+ ``` ts
91
+ function maxAliveYear(birth : number [], death : number []): number {
92
+ const n = birth .length ;
93
+ const counter = new Map <number , number >();
94
+ for (let i = 0 ; i < n ; i ++ ) {
95
+ counter .set (birth [i ], 0 );
96
+ counter .set (death [i ], 0 );
97
+ }
98
+ for (let i = 0 ; i < n ; i ++ ) {
99
+ const start = birth [i ];
100
+ const end = death [i ];
101
+ for (const key of counter .keys ()) {
102
+ if (key >= start && key <= end ) {
103
+ counter .set (key , (counter .get (key ) ?? 0 ) + 1 );
104
+ }
105
+ }
106
+ }
107
+ let res = 0 ;
108
+ let max = 0 ;
109
+ for (const [key, val] of counter ) {
110
+ if (val === max ) {
111
+ res = Math .min (res , key );
112
+ } else if (val > max ) {
113
+ res = key ;
114
+ max = Math .max (max , val );
115
+ }
116
+ }
117
+ return res ;
118
+ }
119
+
120
+ ```
121
+
122
+ ### ** Rust**
123
+
124
+ ``` rust
125
+ impl Solution {
126
+ pub fn max_alive_year (birth : Vec <i32 >, death : Vec <i32 >) -> i32 {
127
+ let n = birth . len ();
128
+ let mut counter = vec! [0 ; 101 ];
129
+ for i in 0 .. n {
130
+ let (start , end ) = (birth [i ] - 1900 , death [i ] - 1900 );
131
+ for j in start ..= end {
132
+ counter [j as usize ] += 1 ;
133
+ }
134
+ }
135
+ let mut res = 0 ;
136
+ let mut max = 0 ;
137
+ for (i , count ) in counter . iter (). enumerate () {
138
+ if * count > max {
139
+ res = i ;
140
+ max = * count ;
141
+ }
142
+ }
143
+ (res + 1900 ) as i32
144
+ }
145
+ }
146
+ ```
147
+
80
148
### ** ...**
81
149
82
150
```
0 commit comments