ปานกลาง 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

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก