1396. 设计地铁系统 - 力扣(Leetcode)
设计题:
设计数据结构
userstartTime int endTime int startStationName string endStatationName string UndergroundSystemuserMap map[int]*user pathMap map[string][]int // 存放对应路程的用时,用于计算平均时间 注意点:go语言针对结构体包含指针的,需要在具体实现前初始化。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 type user struct { id int startTime int endTime int startStationName string endStatationName string }type UndergroundSystem struct { userMap map [int ]*user pathMap map [string ][]int }func Constructor () UndergroundSystem { return UndergroundSystem{make (map [int ]*user),make (map [string ][]int )} }func (this *UndergroundSystem) CheckIn(id int , stationName string , t int ) { this.userMap[id] = &user{id:id} this.userMap[id].startTime = t this.userMap[id].startStationName = stationName }func (this *UndergroundSystem) CheckOut(id int , stationName string , t int ) { useTime := 0 if _,ok := this.userMap[id] ;ok { this.userMap[id].endTime = t this.userMap[id].endStatationName = stationName } mapKey := this.userMap[id].startStationName +"->" + this.userMap[id].endStatationName useTime = this.userMap[id].endTime - this.userMap[id].startTime this.pathMap[mapKey] = append (this.pathMap[mapKey],useTime) } func (this *UndergroundSystem) GetAverageTime(startStation string , endStation string ) float64 { mapKey := startStation +"->" + endStation return average(this.pathMap[mapKey]) }func average (s []int ) float64 { sum := 0 for _,v := range s { sum +=v } return float64 (sum)/float64 (len (s)) }