-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMajorityElement.py
More file actions
63 lines (57 loc) · 1.87 KB
/
MajorityElement.py
File metadata and controls
63 lines (57 loc) · 1.87 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 169. Majority Element
# 229. Majority Element II
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict = {}
for num in nums:
if not dict.get(num):
dict[num] = 1
else:
dict[num] += 1
if dict[num] > len(nums) // 2:
return num
class Solution2:
# 运用多数投票算法,详见:https://blog.csdn.net/kimixuchen/article/details/52787307
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
major1, count1 = 0, 0
major2, count2 = 0, 0
for num in nums:
if num == major1: # 如果数组扫描到的数和当前majority1相等。
count1 += 1
continue
if num == major2: # 如果数组扫描到的数和当前majority2相等。
count2 += 1
continue
if count1 == 0: # 针对count1 = 0时,major1为当前值。
major1 = num
count1 = 1
continue
if count2 == 0: # 针对count2 = 0时,major2为当前值。
major2 = num
count2 = 1
continue
count1 -= 1 # 当前num不是1,2时,将1,2的count消去1
count2 -= 1
count1, count2 = 0, 0
# 再次遍历数组判断count1和count2是不是超过三分之一。
for num in nums:
if num == major1:
count1 += 1
elif num == major2:
count2 += 1
res = []
if count1 > len(nums) // 3:
res.append(major1)
if count2 > len(nums) // 3:
res.append(major2)
return res