911. Online Election

LeetCode medium original: C# #array #csharp #hash-table #leetcode #medium #two-pointers
题目文本会按所选界面语言从俄语翻译;代码保持不变。

Вам given два целочисленных 数组а persons и times. На выборах i-й голос был отдан за person[i] в момент времени times[i]. Для каждого запроса в момент времени t find человека, который лидировал на выборах в момент времени t. Голоса, отданные в момент времени t, будут учитываться в нашем запросе. В случае равенства голосов побеждает тот, кто проголосовал последним (среди равных кандидатов). 实现 класса TopVotedCandidate: TopVotedCandidate(int[] persons, int[] times) Инициализирует объект с 数组ами persons и times. int q(int t) returns номер человека, который лидировал на выборах в момент времени t в соответствии с указанными правилами.

示例:

Input

["TopVotedCandidate", "q", "q", "q", "q", "q", "q"]

[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]

Output

[null, 0, 1, 1, 0, 0, 1]

C# 解法

匹配/原始
using System;
using System.Collections.Generic;
public class TopVotedCandidate {
    private int[] times;
    private List<int> leaders;
    public TopVotedCandidate(int[] persons, int[] times) {
        this.times = times;
        this.leaders = new List<int>();
        Dictionary<int, int> counts = new Dictionary<int, int>();
        int leader = -1;
        foreach (int person in persons) {
            if (!counts.ContainsKey(person)) {
                counts[person] = 0;
            }
            counts[person]++;
            if (!counts.ContainsKey(leader) || counts[person] >= counts[leader]) {
                leader = person;
            }
            leaders.Add(leader);
        }
    }
    public int Q(int t) {
        int left = 0;
        int right = times.Length - 1;
        while (left < right) {
            int mid = (left + right + 1) / 2;
            if (times[mid] <= t) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        return leaders[left];
    }
}

C++ 解法

自动草稿,提交前请检查
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class TopVotedCandidate {
    private vector<int>& times;
    private List<int> leaders;
    public TopVotedCandidate(vector<int>& persons, vector<int>& times) {
        this.times = times;
        this.leaders = new List<int>();
        unordered_map<int, int> counts = new unordered_map<int, int>();
        int leader = -1;
        foreach (int person in persons) {
            if (!counts.count(person)) {
                counts[person] = 0;
            }
            counts[person]++;
            if (!counts.count(leader) || counts[person] >= counts[leader]) {
                leader = person;
            }
            leaders.push_back(leader);
        }
    }
    public int Q(int t) {
        int left = 0;
        int right = times.size() - 1;
        while (left < right) {
            int mid = (left + right + 1) / 2;
            if (times[mid] <= t) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        return leaders[left];
    }
}

Java 解法

匹配/原始
import java.util.*;

class TopVotedCandidate {
    private int[] times;
    private List<Integer> leaders;

    public TopVotedCandidate(int[] persons, int[] times) {
        this.times = times;
        this.leaders = new ArrayList<>();
        Map<Integer, Integer> counts = new HashMap<>();
        int leader = -1;

        for (int person : persons) {
            counts.put(person, counts.getOrDefault(person, 0) + 1);
            if (counts.get(person) >= counts.getOrDefault(leader, 0)) {
                leader = person;
            }
            leaders.add(leader);
        }
    }

    public int q(int t) {
        int left = 0, right = times.length - 1;
        while (left < right) {
            int mid = (left + right + 1) / 2;
            if (times[mid] <= t) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        return leaders.get(left);
    }
}

Go 解法

匹配/原始
package main

import (
    "sort"
)

type TopVotedCandidate struct {
    times   []int
    leaders []int
}

func Constructor(persons []int, times []int) TopVotedCandidate {
    counts := make(map[int]int)
    leader := -1
    leaders := make([]int, len(persons))

    for i, person := range persons {
        counts[person]++
        if counts[person] >= counts[leader] {
            leader = person
        }
        leaders[i] = leader
    }

    return TopVotedCandidate{times, leaders}
}

func (this *TopVotedCandidate) Q(t int) int {
    idx := sort.Search(len(this.times), func(i int) bool {
        return this.times[i] > t
    }) - 1
    return this.leaders[idx]
}

Algorithm

Использовать два 数组а для хранения лиц и времени голосования.

Поддерживать текущий счет для каждого кандидата и текущего лидера на момент времени.

На каждый запрос времени t, find наибольший индекс времени, который не превышает t, и вернуть лидера на этот момент времени.

😎

Vacancies for this task

活跃职位 with overlapping task tags are 已显示.

所有职位
目前还没有活跃职位。