Skip to content

Commit db2edea

Browse files
authored
Create Majority Element - Leetcode 169.py
1 parent 0c6dc37 commit db2edea

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Majority Element - Leetcode 169.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
def majorityElement(self, nums):
3+
counter = {}
4+
for num in nums:
5+
if num in counter:
6+
counter[num] += 1
7+
else:
8+
counter[num] = 1
9+
10+
max_count = -1
11+
ans = -1
12+
for key, val in counter.items():
13+
if val > max_count:
14+
max_count = val
15+
ans = key
16+
17+
return ans
18+
# Time: O(n)
19+
# Space: O(n)
20+
21+
22+
class Solution:
23+
def majorityElement(self, nums: List[int]) -> int:
24+
candidate = None
25+
count = 0
26+
27+
for num in nums:
28+
if count == 0:
29+
candidate = num
30+
31+
count += 1 if candidate == num else -1
32+
33+
return candidate
34+
# Time: O(n)
35+
# Space: O(1)

0 commit comments

Comments
 (0)