1
+ use std:: collections:: HashMap ;
2
+
3
+ struct UndergroundSystem {
4
+ people : HashMap < i32 , ( String , i32 ) > ,
5
+ stations : HashMap < String , HashMap < String , ( i64 , i64 ) > >
6
+ }
7
+
8
+ impl UndergroundSystem {
9
+
10
+ fn new ( ) -> Self {
11
+ Self {
12
+ people : HashMap :: new ( ) ,
13
+ stations : HashMap :: new ( ) ,
14
+ }
15
+ }
16
+
17
+ fn check_in ( & mut self , id : i32 , station_name : String , t : i32 ) {
18
+ self . people . insert ( id, ( station_name, t) ) ;
19
+ }
20
+
21
+ fn check_out ( & mut self , id : i32 , station_name : String , t : i32 ) {
22
+ if let Some ( ( start_station, start) ) = self . people . get ( & id) {
23
+ let ( times, total) = self . stations . entry ( start_station. clone ( ) )
24
+ . or_insert ( HashMap :: new ( ) )
25
+ . entry ( station_name) . or_insert ( ( 0 , 0 ) ) ;
26
+ * times += 1 ;
27
+ * total += ( t - * start) as i64 ;
28
+ }
29
+ }
30
+
31
+ fn get_average_time ( & self , start_station : String , end_station : String ) -> f64 {
32
+ if let Some ( destinations) = self . stations . get ( & start_station) {
33
+ if let Some ( & ( times, total) ) = destinations. get ( & end_station) {
34
+ return total as f64 /( times as f64 ) ;
35
+ }
36
+ }
37
+ 0f64
38
+ }
39
+ }
0 commit comments