โ† All problems

229. Majority Element II

MediumOpen on LeetCodeProblem statement

Problem Statement

229. Majority Element II

Medium


Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

 

Example 1:

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

Example 2:

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

Example 3:

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

 

Constraints:

 

Follow up: Could you solve the problem in linear time and in O(1) space?

Java โ€” hashmap

Source file
class Solution {
    public List<Integer> majorityElement(int[] nums) {
        Map<Integer, Integer> m = new HashMap<>();
        List<Integer> ans = new ArrayList<>();
        for (int i : nums)
            m.put(i, m.getOrDefault(i, 0) + 1);
        int majorityThreshold = nums.length / 3;
        for (Map.Entry<Integer, Integer> e : m.entrySet())
            if (e.getValue() > majorityThreshold)
                ans.add(e.getKey());
        return ans;
    }
}