😕题目描述

😔分析

  • **vote**:存储当前所有候选人的票数情况;
  • **moment**:存储当前投票时刻的最多票数的候选人。

每一次有人来投票,就将判断当前候选人A的票数是否多于前一时刻最多的票数候选人B。如果满足条件则当前的最多票数候选为A,反正则当前时刻最多票数候选人为B。
最后根据时间选择当前时刻之前的投票时间的到最后Q的结果。

😏答案

  1. type TopVotedCandidate struct {
  2. time []int
  3. moment map[int]int
  4. }
  5. func Constructor(persons []int, times []int) TopVotedCandidate {
  6. votes_ := make(map[int]int)
  7. moment_ := make(map[int]int)
  8. moment_[times[0]] = persons[0]
  9. votes_[persons[0]]++
  10. for i := 1; i < len(persons); i++ {
  11. if votes_[persons[i]]+1 >= votes_[moment_[times[i-1]]] {
  12. moment_[times[i]] = persons[i]
  13. } else {
  14. moment_[times[i]] = moment_[times[i-1]]
  15. }
  16. votes_[persons[i]]++
  17. }
  18. for k, v := range moment_ {
  19. fmt.Printf("%d : %d\n", k, v)
  20. }
  21. return TopVotedCandidate{
  22. moment: moment_,
  23. time : times,
  24. }
  25. }
  26. func (this *TopVotedCandidate) Q(t int) int {
  27. for i, v := range this.time {
  28. if v > t {
  29. fmt.Printf("%d-%d\n", v, this.moment[this.time[i-1]])
  30. return this.moment[this.time[i-1]]
  31. }
  32. }
  33. return this.moment[this.time[len(this.time) - 1]]
  34. }