forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
majority-element-ii.py
52 lines (43 loc) · 1.57 KB
/
majority-element-ii.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Time: O(n)
# Space: O(1)
# Given an integer array of size n,
# find all elements that appear more than [n/3] times.
# The algorithm should run in linear time and in O(1) space.
import collections
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
k, n, cnts = 3, len(nums), collections.defaultdict(int)
for i in nums:
cnts[i] += 1
# Detecting k items in cnts, at least one of them must have exactly
# one in it. We will discard those k items by one for each.
# This action keeps the same mojority numbers in the remaining numbers.
# Because if x / n > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true.
if len(cnts) == k:
for j in cnts.keys():
cnts[j] -= 1
if cnts[j] == 0:
del cnts[j]
# Resets cnts for the following counting.
for i in cnts.keys():
cnts[i] = 0
# Counts the occurrence of each candidate integer.
for i in nums:
if i in cnts:
cnts[i] += 1
# Selects the integer which occurs > [n / k] times.
result = []
for i in cnts.keys():
if cnts[i] > n / k:
result.append(i)
return result
def majorityElement2(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return [i[0] for i in collections.Counter(nums).items() if i[1] > len(nums) / 3]