911. Online Election

Link

Solution

class TopVotedCandidate {
    Map<Integer, Integer> voteMap;
    TreeMap<Integer, Integer> tmap;
    public TopVotedCandidate(int[] persons, int[] times) {
        voteMap = new HashMap<>();
        tmap = new TreeMap<>();
        int max = persons[0];
        for(int i = 0; i < persons.length; i++){
            
            voteMap.compute(persons[i], (k,v)->{
                if(v == null) return 1;
                return v+1;
            });
            if(voteMap.get(max) <= voteMap.get(persons[i])) max = persons[i];
            
            tmap.put(times[i], max);
        }
    }
    
    public int q(int t) {
        return tmap.floorEntry(t).getValue();
    }
}

Last updated

Was this helpful?