สมมติว่ามีรายการตัวเลข nums ความยาว n แต่ละตัวแทนเสียง ต้องการหา ID ผู้สมัครที่ได้เสียงมากกว่า floor(n/2) หากไม่มีคืน -1
ตัวอย่าง: nums = [6, 6, 2, 2, 3, 3, 3, 3, 3] ผลลัพธ์คือ 3
ขั้นตอนการแก้ปัญหา
l = len(nums)- นับความถี่ด้วย
Counter - วนแต่ละค่า
iและจำนวนj:- ถ้า
j > l//2: คืนi
- ถ้า
- คืน -1
ตัวอย่างโค้ด
class Solution:
def solve(self, nums):
l = len(nums)
from collections import Counter
count = Counter(nums)
for i, j in count.items():
if j > (l // 2):
return i
return -1
ob = Solution()
nums = [6, 6, 2, 2, 3, 3, 3, 3, 3]
print(ob.solve(nums))
อินพุต
[6, 6, 2, 2, 3, 3, 3, 3, 3]
เอาต์พุต
3