😕题目描述
😔分析
**vote**:存储当前所有候选人的票数情况;**moment**:存储当前投票时刻的最多票数的候选人。
每一次有人来投票,就将判断当前候选人A的票数是否多于前一时刻最多的票数候选人B。如果满足条件则当前的最多票数候选为A,反正则当前时刻最多票数候选人为B。
最后根据时间选择当前时刻之前的投票时间的到最后Q的结果。
😏答案
type TopVotedCandidate struct {time []intmoment map[int]int}func Constructor(persons []int, times []int) TopVotedCandidate {votes_ := make(map[int]int)moment_ := make(map[int]int)moment_[times[0]] = persons[0]votes_[persons[0]]++for i := 1; i < len(persons); i++ {if votes_[persons[i]]+1 >= votes_[moment_[times[i-1]]] {moment_[times[i]] = persons[i]} else {moment_[times[i]] = moment_[times[i-1]]}votes_[persons[i]]++}for k, v := range moment_ {fmt.Printf("%d : %d\n", k, v)}return TopVotedCandidate{moment: moment_,time : times,}}func (this *TopVotedCandidate) Q(t int) int {for i, v := range this.time {if v > t {fmt.Printf("%d-%d\n", v, this.moment[this.time[i-1]])return this.moment[this.time[i-1]]}}return this.moment[this.time[len(this.time) - 1]]}
