Try โ€‚โ€‰HackMD

Majority Element
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More โ†’

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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

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

Solution

Solution 1: First attempt

class Solution: def majorityElement(self, nums: List[int]) -> int: # O(n) time complexity. # O(n) space complexity. dic = {} m = len(nums)//2 for elt in nums: if not elt in dic: dic[elt] = 1 else: dic[elt] += 1 if dic[elt] > m: return elt return nums[0]

Solution 2: Boyer-Moore Voting Algorithm

class Solution: def majorityElement(self, nums: List[int]) -> int: # O(n) time complexity. # O(1) space complexity. count = 0 candidate = None for num in nums: if count == 0: candidate = num count += (1 if num == candidate else -1) return candidate