911. Online Election
Вам 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 표시됨.