DEV Community

özkan pakdil
özkan pakdil

Posted on

169. 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 1:

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

Example 2:

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

Solution

    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> m = new HashMap<>();
        for (int n : nums) {
            m.put(n, m.getOrDefault(n, 0) + 1);
        }
        Optional<Map.Entry<Integer, Integer>> maxEntry = m.entrySet()
                .stream()
                .max(Comparator.comparing(Map.Entry::getValue));
        return maxEntry.get()
                .getKey();
    }
Enter fullscreen mode Exit fullscreen mode

better solution

public int majorityElement(int[] nums) {
    int major = 0, count = 0;
    for (int i = 0; i < nums.length; i++) {
        if (count == 0) major = nums[i];
        if (major == nums[i]) count++;
        else count--;
    }
    return major;
}
Enter fullscreen mode Exit fullscreen mode

reference: https://leetcode.com/problems/majority-element/description/?source=submission-ac

Top comments (0)