Skip to content

Commit 82de5e4

Browse files
committed
D. J.:
- Added leetcode problem and solution for 169 Majority Element
1 parent 01b4f21 commit 82de5e4

File tree

3 files changed

+39
-2
lines changed

3 files changed

+39
-2
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,17 @@
33
This repository contains awesome LeetCode problems and solutions written in Python to prepare for coding interviews.
44

55
## Leetcode Problems & Solutions 💻
6+
67
- [26 Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)
78
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
89
- [80 Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/)
910
- [88 Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/description/)
10-
11+
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
1112

1213
## Development 🔧
14+
1315
Contributions are welcome!
1416

1517
Please fork the repository and submit a pull request.
1618

17-
Make sure to follow the coding standards and write tests for any new leetcode problem or bug fix.
19+
Make sure to follow the coding standards and write tests for any new leetcode problem or bug fix.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def majorityElement(self, nums: List[int]) -> int:
6+
"""
7+
Given an array nums of size n, return the majority element.
8+
9+
The majority element is the element that appears more than ⌊n / 2⌋ times.
10+
You may assume that the majority element always exists in the array.
11+
"""
12+
counts = {}
13+
for num in nums:
14+
if num not in counts:
15+
counts[num] = 1
16+
else:
17+
counts[num] += 1
18+
return max(counts, key=lambda k: counts[k])

tests/test_169_majority_element.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._169_majority_element import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([3, 2, 3], 3),
12+
([2, 2, 1, 1, 1, 2, 2], 2),
13+
],
14+
)
15+
def test_func(nums: List[int], expected: int):
16+
majority_element = Solution().majorityElement(nums)
17+
assert majority_element == expected

0 commit comments

Comments
 (0)