forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajority_number_iii.py
More file actions
33 lines (32 loc) · 1.01 KB
/
majority_number_iii.py
File metadata and controls
33 lines (32 loc) · 1.01 KB
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
# -*- coding: utf-8 -*-
class Solution:
"""
@param nums: A list of integers
@param k: As described
@return: The majority number
"""
def majorityNumber(self, nums, k):
# write your code here
# 还是借鉴majority_number_ii.py的算法
statistics = {}
for num in nums:
if num in statistics:
statistics[num] += 1
elif len(statistics) < k:
statistics[num] = 1
else:
keys = []
for key in statistics:
statistics[key] -= 1
if statistics[key] == 0:
keys.append(key)
for key in keys:
del(statistics[key])
ret, _max_count = None, 0
for num in nums:
if num in statistics:
statistics[num] += 1
if statistics[num] > _max_count:
_max_count = statistics[num]
ret = num
return ret