Skip to content

Commit 50387c1

Browse files
committed
Majority Element
1 parent e60b119 commit 50387c1

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

169 Majority Element.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'''
2+
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
3+
4+
You may assume that the array is non-empty and the majority element always exist in the array.
5+
'''
6+
7+
class Solution(object):
8+
def majorityElement(self, nums):
9+
"""
10+
:type nums: List[int]
11+
:rtype: int
12+
"""
13+
result = None
14+
count = 0
15+
for num in nums:
16+
if count == 0:
17+
result = num
18+
if result == num:
19+
count += 1
20+
else:
21+
count -= 1
22+
return result
23+
24+
25+
if __name__ == "__main__":
26+
assert Solution().majorityElement([1, 2, 2, 3, 3, 3, 3]) == 3
27+
assert Solution().majorityElement([3, 3, 3, 3, 1, 1, 2]) == 3

0 commit comments

Comments
 (0)