-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmajority.py
More file actions
35 lines (28 loc) · 835 Bytes
/
majority.py
File metadata and controls
35 lines (28 loc) · 835 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
"""
# Logic1: Time limit exceeded for the brute force solution
n = len(nums)
count = 0
for ch in nums:
if nums.count(ch) > n//2:
return ch
"""
"""
# Logic2: using hashmap - 100 pass
n = len(nums)
counts = {}
for ch in nums:
if ch not in counts:
counts[ch] = 0
counts[ch] += 1
for k,v in counts.items():
if v > n//2:
return k
"""
# technically good solution - one liner 100pass
return sorted(nums)[len(nums)//2]