LeetCode 169. Majority Element

Post by ailswan Oct.10, 2023

169. Majority Element

Problem Statement

link: https://leetcode.com/problems/majority-element/ https://leetcode.cn/problems/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 = [3,2,3] Output: 3

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

Solution Approach

Algorithm

Implement

    class Solution:
    dic = Counter(nums)
      l = len(nums)
      for k in dic:
          if dic[k] > (l // 2):
              return k

class Solution:
  def majorityElement(self, nums: List[int]) -> int:
      counts = collections.Counter(nums)
      return max(counts.keys(), key=counts.get)