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 7cbc38f

Browse files
committed
Create majority_element.py
1 parent 9106bf9 commit 7cbc38f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎arrays_hashing/majority_element.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
Given an array nums of size n, return the majority element.
3+
4+
The majority element is the element that appears more than ⌊n / 2⌋ times
5+
in the array. You may assume that the majority element always exists in the array.
6+
7+
Example:
8+
Input: nums = [5, 5, 1, 1, 1, 5, 5]
9+
Output: 5
10+
"""
11+
from typing import List
12+
# Method 1:
13+
class Solution:
14+
def majorityElement(self, nums: List[int]) -> int:
15+
16+
count = {}
17+
18+
for n in nums:
19+
if n not in count:
20+
count[n] = 1
21+
else:
22+
count[n] += 1
23+
for k,v in count.items():
24+
if v > len(nums) // 2:
25+
return k
26+
27+
# Method 2:
28+
class Solution:
29+
def majorityElement(self, nums: List[int]) -> int:
30+
31+
nums = sorted(nums)
32+
33+
return nums[len(nums)//2]
34+
35+
# Method 3:
36+
class Solution:
37+
def majorityElement(self, nums: List[int]) -> int:
38+
39+
res = 0
40+
count = 0
41+
42+
for n in nums:
43+
44+
if count == 0:
45+
res = n
46+
if n == res:
47+
count += 1
48+
else:
49+
count -= 1
50+
return res
51+
52+
53+
54+
55+

0 commit comments

Comments
(0)

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