Skip to content

Commit 7c1880f

Browse files
committed
added Majority Element (easy)
1 parent 043cf25 commit 7c1880f

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

Easy/MajorityElement/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
# Majority Element
3+
[Leetcode Link](https://leetcode.com/problems/majority-element/)
4+
5+
## Problem:
6+
7+
Given an array of size `n`, find the majority element. The majority element is the element that appears **more than** `⌊ n/2 ⌋` times.
8+
9+
You may assume that the array is non-empty and the majority element always exist in the array.
10+
11+
## Example:
12+
13+
```
14+
Input: [3,2,3]
15+
Output: 3
16+
```
17+
```
18+
Input: [2,2,1,1,1,2,2]
19+
Output: 2
20+
```

Easy/MajorityElement/solution.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List
2+
import math
3+
4+
5+
def majorityElement(nums: List[int]) -> int:
6+
numCounter = dict()
7+
for num in nums:
8+
numCounter[num] = numCounter.get(num, 0) + 1
9+
for k, v in numCounter.items():
10+
if v > math.floor(len(nums)/2):
11+
return k
12+
return None
13+
14+
15+
# test driver
16+
input = [3, 2, 3]
17+
print("Input:", input)
18+
print("Output:", majorityElement(input))
19+
print()
20+
21+
input = [2, 2, 1, 1, 1, 2, 2]
22+
print("Input:", input)
23+
print("Output:", majorityElement(input))
24+
print()

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Languages used: Java and Python
2525
- [Maximum Product of Three Numbers](Easy/MaxProductofThreeNumbers)
2626
- [Maximize Sum Of Array After K Negations](Easy/MaximizeSumAfterKNegations)
2727
- [House Robber](Easy/HouseRobber)
28+
- [Majority Element](Easy/MajorityElement)
2829
- Medium
2930
- [Minimum Add to Make Parentheses Valid](Medium/MinimumAddtoMakeParenthesesValid)
3031
- [Distribute Coins in Binary Tree](Medium/DistributionCoinsInBinaryTree)

0 commit comments

Comments
 (0)