中級 0件解決済み 正答率0%

Plurality Election

Count one vote per voter and return every candidate with the most votes.

このチャレンジで学べること

  • Count votes per candidate
  • Ignore invalid votes
  • Return every candidate tied for the top count

問題

翻訳を表示

The student council election is a simple plurality vote: each voter writes one candidate's name, and the candidate with the most votes wins. A vote for a name that is not on the candidate list (a typo or a write-in) is thrown out. If several candidates share the highest count, they all win and share the office.

Implement plurality_election(candidates, votes).

Input

candidates: The candidates' names, all different.

votes: One name per voter. Names must match exactly, including case.

Output

Return the names of all winners in the order they appear in candidates. If no valid votes were cast, every candidate is tied at 0 and all are returned.

制約

1 ≤ length of candidates ≤ 20

0 ≤ length of votes ≤ 1000

Names have 1 to 20 ASCII letters

例

例 1
入力:
candidates = ["Ava", "Ben", "Cruz"]
votes = ["Ben", "Ava", "Ben", "Cruz", "Ben"]

期待される出力:
expected = ["Ben"]
入力:
std::vector<std::string> candidates = {"Ava", "Ben", "Cruz"};
std::vector<std::string> votes = {"Ben", "Ava", "Ben", "Cruz", "Ben"};

期待される出力:
std::vector<std::string> expected = {"Ben"};
入力:
string[] candidates = new string[] {"Ava", "Ben", "Cruz"};
string[] votes = new string[] {"Ben", "Ava", "Ben", "Cruz", "Ben"};

期待される出力:
string[] expected = new string[] {"Ben"};

解説

Ben has 3 votes, more than Ava and Cruz with 1 each, so ["Ben"].

例 2
入力:
candidates = ["Ava", "Ben", "Cruz"]
votes = ["Cruz", "Ava", "ava", "Dana"]

期待される出力:
expected = ["Ava", "Cruz"]
入力:
std::vector<std::string> candidates = {"Ava", "Ben", "Cruz"};
std::vector<std::string> votes = {"Cruz", "Ava", "ava", "Dana"};

期待される出力:
std::vector<std::string> expected = {"Ava", "Cruz"};
入力:
string[] candidates = new string[] {"Ava", "Ben", "Cruz"};
string[] votes = new string[] {"Cruz", "Ava", "ava", "Dana"};

期待される出力:
string[] expected = new string[] {"Ava", "Cruz"};

解説

ava and Dana are thrown out, leaving Ava and Cruz tied at 1: ["Ava", "Cruz"].

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Start every candidate at 0 votes so candidates without votes still count.

ヒント 2

Only count a vote when the name is exactly a candidate.

ヒント 3

Find the highest count first, then collect everyone with that count in list order.

目安の計算量

O(c + v) time, O(c) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。