Skip to content

Commit a5f0a00

Browse files
committed
Update index.ts
1 parent e7f84b1 commit a5f0a00

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

design-underground-system/index.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,35 @@
11
export default class UndergroundSystem {
2+
id2info = new Map<number, [string, number]>();
3+
station2time = new Map<string, number[]>();
24
constructor() {
35
}
46

57
checkIn(id: number, stationName: string, t: number): void {
8+
const info: [string, number] = [stationName, t];
9+
this.id2info.set(id, info);
610
}
711

812
checkOut(id: number, stationName: string, t: number): void {
13+
const info = this.id2info.get(id);
14+
if (info) {
15+
const key = JSON.stringify([info[0], stationName]);
16+
const time = this.station2time.get(
17+
key,
18+
) ?? [];
19+
time.push(t - info[1]);
20+
this.station2time.set(key, time);
21+
} else {
22+
throw Error("accident");
23+
}
924
}
1025

1126
getAverageTime(startStation: string, endStation: string): number {
27+
const key = JSON.stringify([startStation, endStation]);
28+
const time = this.station2time.get(
29+
key,
30+
);
31+
if (!time) throw Error("accident");
32+
33+
return time.reduce((a, v) => a + v, 0) / time.length;
1234
}
1335
}

0 commit comments

Comments
 (0)