169.majority-element
sort, runtime 99.5%
Published in
1 min readApr 6, 2019
Solution 1: Counter
class Solution:
def majorityElement(self, nums: List[int]) -> int:
from collections import Counter
num, count = Counter(nums).most_common(1)[0]
return num# ✔ 44/44 cases passed (80 ms)
# ✔ Your runtime beats 11.84 % of python3 submissions
# ✔ Your memory usage beats 5.18 % of python3 submissions (14.3 MB)
Solution 2: defaultdict
class Solution:
def majorityElement(self, nums: List[int]) -> int:
from collections import defaultdict
counts = defaultdict(int)
threshold = len(nums) / 2
for num in nums:
counts[num] += 1
if counts[num] > threshold:
return num# ✔ 44/44 cases passed (56 ms)
# ✔ Your runtime beats 52.06 % of python3 submissions
# ✔ Your memory usage beats 5.18 % of python3 submissions (14.5 MB)
Solution 3: sort
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums)//2]# ✔ 44/44 cases passed (44 ms)
# ✔ Your runtime beats 99.5 % of python3 submissions
# ✔ Your memory usage beats 5.18 % of python3 submissions (14.2 MB)