We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 0c6dc37 commit db2edeaCopy full SHA for db2edea
Majority Element - Leetcode 169.py
@@ -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
23
+ def majorityElement(self, nums: List[int]) -> int:
24
+ candidate = None
25
+ count = 0
26
27
28
+ if count == 0:
29
+ candidate = num
30
31
+ count += 1 if candidate == num else -1
32
33
+ return candidate
34
35
+ # Space: O(1)
0 commit comments