LeetCode: Design Underground System Solution
Approach
Init two hash tables
- one stores the k-v pair of current check-in info of a customer
- one stores the k-v pairs of route and its accumulated total time
Implementation
1var UndergroundSystem = function () {2 this.checkInMap = new Map()3 this.routeTotalTimeMap = new Map()4}56/**7 * @param {number} id8 * @param {string} stationName9 * @param {number} t10 * @return {void}11 */12UndergroundSystem.prototype.checkIn = function (id, stationName, t) {13 this.checkInMap.set(id, { stationName, t })14}1516/**17 * @param {number} id18 * @param {string} stationName19 * @param {number} t20 * @return {void}21 */22UndergroundSystem.prototype.checkOut = function (id, stationName, t) {23 const route = `${this.checkInMap.get(id).stationName} - ${stationName}`24 if (!this.routeTotalTimeMap.has(route)) {25 this.routeTotalTimeMap.set(route, {26 total: 0,27 count: 0,28 })29 }30 const routeTotalTime = this.routeTotalTimeMap.get(route)31 this.routeTotalTimeMap.set(route, {32 total: routeTotalTime.total + (t - this.checkInMap.get(id).t),33 count: routeTotalTime.count + 1,34 })35 this.checkInMap.delete(id)36}3738/**39 * @param {string} startStation40 * @param {string} endStation41 * @return {number}42 */43UndergroundSystem.prototype.getAverageTime = function (44 startStation,45 endStation46) {47 const route = `${startStation} - ${endStation}`48 const routeTotalTime = this.routeTotalTimeMap.get(route)49 return routeTotalTime.total / routeTotalTime.count50}5152/**53 * Your UndergroundSystem object will be instantiated and called as such:54 * var obj = new UndergroundSystem()55 * obj.checkIn(id,stationName,t)56 * obj.checkOut(id,stationName,t)57 * var param_3 = obj.getAverageTime(startStation,endStation)58 */
Comments
Loading comments...
Tags
leetcode
hash table
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Reordered Power Of 2
Mar 22, 2021
Previous Post
LeetCode: Second Largest Digit In A String
Mar 21, 2021