problem:https://leetcode.com/problems/online-election/
Binary search problem, mainly based on two time points, the first pre-calculated current time point corresponding to the voter, to keep the hashmap. After finding the time by half, and then find the corresponding voter by hash.
class TopVotedCandidate { public: unordered_map<int,int> vote; vector<int> time; TopVotedCandidate(vector<int>& persons, vector<int>& times) { unordered_map<int,int> score; time = times; int maxscore = 0; int maxperson; for(int i = 0;i < persons.size();i++) { score[persons[i]]++; if(score[persons[i]] >= maxscore) { maxscore = score[persons[i]]; maxperson = persons[i]; } vote[times[i]] = maxperson; } } int q(int t) { auto it = upper_bound(time.begin(),time.end(),t); it = prev(it); return vote[*it]; } }; /** * Your TopVotedCandidate object will be instantiated and called as such: * TopVotedCandidate* obj = new TopVotedCandidate(persons, times); * int param_1 = obj->q(t); */