forked from shichao-an/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution2.py
More file actions
25 lines (23 loc) · 631 Bytes
/
solution2.py
File metadata and controls
25 lines (23 loc) · 631 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
"""
Given an array of size n, find the majority element. The majority element is
the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always
exist in the array.
"""
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
cand = None
for c in nums:
if count == 0:
cand = c
count += 1
elif cand == c:
count += 1
else:
count -= 1
return cand