BudiBadu Logo

Majority Element

Hash Table Easy 0 views
Like0

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 can solve this with a hash map by counting each number, then returning the one whose count is above n/2.

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [1]
Output: 1

Algorithm Flow

Recommendation Algorithm Flow for Majority Element - Budibadu
Recommendation Algorithm Flow for Majority Element - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int majority_element(int[] nums) {
        Map<Integer, Integer> freq = new HashMap<>();
        int limit = nums.length / 2;
        for (int x : nums) {
            freq.put(x, freq.getOrDefault(x, 0) + 1);
            if (freq.get(x) > limit) return x;
        }
        return nums.length > 0 ? nums[0] : 0;
    }
}