Skip to content

Commit bba7018

Browse files
committed
主元素
1 parent d2a627f commit bba7018

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

majority_number.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param nums: A list of integers
6+
@return: The majority number
7+
"""
8+
def majorityNumber(self, nums):
9+
# write your code here
10+
# 借鉴majority_number_ii.py的算法,复杂度降低到O(n)。
11+
ret, count = 0, 0
12+
for i in xrange(len(nums)):
13+
if count == 0:
14+
ret = nums[i]
15+
count = 1
16+
else:
17+
count = (count + 1) if ret == nums[i] else (count - 1)
18+
return ret

0 commit comments

Comments
 (0)