169. Majority Element
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:
Input: nums = [2,2,1,1,1,2,2] Output: 2
def majorityElement(nums):
majority = None
count = 0
for n in nums:
if majority is None:
count = 1
majority = n
elif n == majority:
count += 1
else:
count -= 1
if count == 0:
majority = None
return majority
Comments
Post a Comment