Description

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

1
2
Input: nums = [3,2,3]
Output: 3

Example 2:

1
2
Input: nums = [2,2,1,1,1,2,2]
Output: 2

Constraints:

1
2
3
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109

The input is generated such that a majority element will exist in the array.

Approach

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = 0
n = -1
for i in nums:
if i == n:
count +=1
elif count < 1:
n = i
else:
count -=1
return n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = 0
candidate = None

for num in nums:
if count == 0:
candidate = num

if num == candidate:
count += 1
else:
count -= 1

return candidate