|
1 | 1 | class UndergroundSystem {
|
2 |
| - Map<Integer, String> checkInMap; |
3 |
| - Map<String, Integer> timeMap; |
4 |
| - Map<String, Integer> countMap; |
| 2 | + |
| 3 | + private Map<String, Integer> totalTimeFromStartToEndStation; |
| 4 | + private Map<String, Integer> numberOfCustomersFromStartToEndStation; |
| 5 | + private Map<Integer, Integer> customerIdToStartTime; |
| 6 | + private Map<Integer, String> customerIdToStartStation; |
| 7 | + |
5 | 8 | public UndergroundSystem() {
|
6 |
| - checkInMap = new HashMap<>(); |
7 |
| - timeMap = new HashMap<>(); |
8 |
| - countMap = new HashMap<>(); |
| 9 | + this.totalTimeFromStartToEndStation = new HashMap<>(); |
| 10 | + this.numberOfCustomersFromStartToEndStation = new HashMap<>(); |
| 11 | + this.customerIdToStartTime = new HashMap<>(); |
| 12 | + this.customerIdToStartStation = new HashMap<>(); |
9 | 13 | }
|
10 | 14 |
|
11 | 15 | public void checkIn(int id, String stationName, int t) {
|
12 |
| - checkInMap.put(id, stationName + "," + t); |
| 16 | + this.customerIdToStartTime.put(id, t); |
| 17 | + this.customerIdToStartStation.put(id, stationName); |
13 | 18 | }
|
14 | 19 |
|
15 | 20 | public void checkOut(int id, String stationName, int t) {
|
16 |
| - String val = checkInMap.get(id); |
17 |
| - String prevStationName = val.split(",")[0]; |
18 |
| - int prevTime = Integer.parseInt(val.split(",")[1]); |
19 |
| - String key = prevStationName + "|" + stationName; |
20 |
| - timeMap.put(key, timeMap.getOrDefault(key, 0) + t - prevTime); |
21 |
| - countMap.put(key, countMap.getOrDefault(key, 0) + 1); |
| 21 | + int totalTime = t - this.customerIdToStartTime.get(id); |
| 22 | + String key = this.customerIdToStartStation.get(id) + "|" + stationName; |
| 23 | + this.totalTimeFromStartToEndStation.put(key, this.totalTimeFromStartToEndStation.getOrDefault(key, 0) + totalTime); |
| 24 | + this.numberOfCustomersFromStartToEndStation.put(key, this.numberOfCustomersFromStartToEndStation.getOrDefault(key, 0) + 1); |
22 | 25 | }
|
23 | 26 |
|
24 | 27 | public double getAverageTime(String startStation, String endStation) {
|
25 | 28 | String key = startStation + "|" + endStation;
|
26 |
| - return ((double) timeMap.get(key)) / countMap.get(key); |
27 |
| - } |
| 29 | + return this.totalTimeFromStartToEndStation.get(key) / (double) (this.numberOfCustomersFromStartToEndStation.get(key)); |
| 30 | + } |
28 | 31 | }
|
29 | 32 |
|
30 | 33 | /**
|
|
0 commit comments