Skip to content

Commit 407ec1b

Browse files
committed
主元素 III
1 parent 79ee689 commit 407ec1b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

majority_number_iii.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param nums: A list of integers
6+
@param k: As described
7+
@return: The majority number
8+
"""
9+
def majorityNumber(self, nums, k):
10+
# write your code here
11+
# 还是借鉴majority_number_ii.py的算法
12+
statistics = {}
13+
for num in nums:
14+
if num in statistics:
15+
statistics[num] += 1
16+
elif len(statistics) < k:
17+
statistics[num] = 1
18+
else:
19+
keys = []
20+
for key in statistics:
21+
statistics[key] -= 1
22+
if statistics[key] == 0:
23+
keys.append(key)
24+
for key in keys:
25+
del(statistics[key])
26+
ret, _max_count = None, 0
27+
for num in nums:
28+
if num in statistics:
29+
statistics[num] += 1
30+
if statistics[num] > _max_count:
31+
_max_count = statistics[num]
32+
ret = num
33+
return ret

0 commit comments

Comments
 (0)