911. 在线选举
给你两个整数数组 persons 和 times 。在选举中,第 i 张票是在时刻为 times[i] 时投给候选人 persons[i] 的。
对于发生在时刻 t 的每个查询,需要找出在 t 时刻在选举中领先的候选人的编号。
在 t 时刻投出的选票也将被计入我们的查询之中。在平局的情况下,最近获得投票的候选人将会获胜。
实现 TopVotedCandidate 类:
TopVotedCandidate(int[] persons, int[] times) 使用 persons 和 times 数组初始化对象。
int q(int t) 根据前面描述的规则,返回在时刻 t 在选举中领先的候选人的编号。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/online-election
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class TopVotedCandidate {
    private List<Integer> tops;
    private Map<Integer, Integer> voteCounts;
    private int[] times;
    public TopVotedCandidate(int[] persons, int[] times) {
        tops = new ArrayList<>();
        voteCounts = new HashMap<>();
        voteCounts.put(-1, -1);
        int top = -1;
        for (int i = 0; i < persons.length; ++i) {
            int p = persons[i];
            voteCounts.put(p, voteCounts.getOrDefault(p, 0) + 1);
            if (voteCounts.get(p) >= voteCounts.get(top)) {
                top = p;
            }
            tops.add(top);
        }
        this.times = times;
    }
    public int q(int t) {
        int ans = 0;
        int l = 0, r = times.length - 1;
        // 找到满足 times[l] <= t 的最大的 l
        while (l <= r) {
            int m = (l + r) >> 1;
            if (times[m] <= t) {
                ans = m;
                l = m + 1;
            } else {
                r = m - 1;
            }
        }
        return tops.get(ans);
    }
}
    心之所向,素履以往 生如逆旅,一苇以航

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号