Majority Element

by atalaykutlay

Solution to "Majority Element" on Leetcode.

Majority Element
1class Solution:
2    def majorityElement(self, nums: List[int]) -> int:
3        seen = defaultdict(int)
4        for index, num in enumerate(nums):
5            seen[num] += 1
6            if seen[num] > len(nums)/2:
7                return num
8        
9

✨ Code Explanation ✨

This code is defining a class called "Solution" which has a method called "majorityElement". The method takes a list of integers as input and returns the majority element in the list, which is defined as the element that appears more than n/2 times, where n is the total number of elements in the list. The code first initializes a dictionary called "seen" using the "defaultdict" class. This dictionary will store the count of each element seen so far in the "nums" list. Then, a for loop is used to iterate over the elements in "nums". The "enumerate" function is used to get both the index and the element during each iteration. Inside the loop, the code increments the count of the current element in the "seen" dictionary by 1 using the "+=" operator. Next, an if statement checks if the count of the current element is greater than half the length of "nums". If it is, then the current element is the majority element, so it is returned. If no majority element is found, the function will implicitly return None.

Share

Share
Video
A cool 10 sec video.
Share
Detailed
Title, description, and syntax highlighted code.
Share
Simple
Syntax highlighted code with gradient background colored presentation.

Comments

It looks like there is no comment for this snippet. Leave the first one!
You need to login to send a comment.

Similar Snippets

Count Number of Texts
Count Number of Texts

Solution to "Count Number of Texts" question on Leetcode.

Language: python12 months ago
Quicksort in Python
Quicksort in Python

An easy quicksort implementation in Python.

Language: python13 months ago
Second Minimum Node In a Binary Tree
Second Minimum Node In a Binary Tree

Solution to "Second Minimum Node In a Binary Tree" on Leetcode.

Language: python11 months ago