Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 14bbc3e

Browse files
committed
Add Majority Element solution
1 parent eb91bc9 commit 14bbc3e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

‎arrays/169_Majority_Element.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def majority_element(nums: list[int]) -> int:
2+
"""Finds the majority element in a list of integers.
3+
4+
The majority element is the element that appears more than ⌊n / 2⌋ times,
5+
where n is the size of the array. It is assumed that the majority element always exists.
6+
7+
:param nums: A list of integers where the majority element is to be found.
8+
:return: The majority element in the list.
9+
"""
10+
11+
counter = 1
12+
current_majority_element = nums[0]
13+
14+
for num in nums[1:]:
15+
if current_majority_element != num:
16+
if counter:
17+
counter -= 1
18+
if counter == 0:
19+
current_majority_element = num
20+
counter = 1
21+
else:
22+
counter += 1
23+
24+
return current_majority_element
25+
26+
27+
assert majority_element(nums=[3,2,3]) == 3, 'Test 1 failed'
28+
assert majority_element(nums=[2,2,1,1,1,2,2]) == 2, 'Test 2 failed'
29+
assert majority_element(nums=[6,5,5]) == 5, 'Test 3 failed'

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /