-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathMajority Number.py
More file actions
44 lines (31 loc) · 945 Bytes
/
Majority Number.py
File metadata and controls
44 lines (31 loc) · 945 Bytes
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
"""
Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find
it.
Example
For [1, 1, 1, 1, 2, 2, 2], return 1
Challenge
O(n) time and O(1) space
"""
__author__ = 'Danyang'
class Solution:
def majorityNumber(self, nums):
"""
Moore's Voting Algorithm
greedy half
:param nums: A list of integers
:return: The majority number
"""
cnt = 0
maj = 0
for ind, num in enumerate(nums):
if num == nums[maj]:
cnt += 1
else:
cnt -= 1 # every time --, discard 2 different numbers
if cnt < 0:
maj = ind
cnt = 1
# assured that the majority exists, otherwise need to double check
return nums[maj]
if __name__ == "__main__":
assert Solution().majorityNumber([1, 1, 1, 2, 2, 2, 2, 1, 1]) == 1