[二分搜索] leetcode 911 Online Election

problem:https://leetcode.com/problems/online-election/

         二分搜索题,主要是根据时间来二分,先预先计算好当前时间点对应的选举人,存到hashmap中。之后通过二分找到时间,再通过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);
 */

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11285595.html