-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path169.majority-element.py
More file actions
46 lines (34 loc) · 1.04 KB
/
169.majority-element.py
File metadata and controls
46 lines (34 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from typing import List
from collections import defaultdict
import heapq
# O(n) space complexity also the popping from the heap is not O(n)
class Solution_one:
def majorityElement(self, nums: List[int]) -> int:
frequency: dict[int, int] = defaultdict(int)
for i in nums:
frequency[i] += 1
freq = [(-a, b) for b, a in frequency.items()]
heapq.heapify(freq)
return heapq.heappop(freq)[1]
class Solution_two:
def majorityElement(self, nums: List[int]) -> int:
count: dict[int, int] = defaultdict(int)
majority = 0
for i in nums:
count[i] += 1
if count[i] > count[majority]:
majority = i
print(majority)
print(count)
return majority
# @leet start
class Solution:
def majorityElement(self, nums: List[int]) -> int:
majority = 0
ans = 0
for i in nums:
if majority == 0:
ans = i
majority += 1 if ans == i else -1
return ans
# @leet end