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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay