Post

[Java] Majority Element

[Java] Majority Element

Feel free to leave a comment or contact me if you spot any errors or have feedback. I’m always open to learning!

[Java] Remove Duplicates from Sorted Array

LeetCode Problem #169 šŸ”— LeetCode Link

Espeically, this problem is in the Must-do List for Interview Prep in Leetcode.

Description

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

Example 1

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

Example 2

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

Constraints

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> cntHashMap = new HashMap<>();
        int maxElement = 0;
        int maxCount = 0;

        for (int num : nums) {
            if (cntHashMap.containsKey(num)) {
                cntHashMap.put(num, cntHashMap.get(num)+1);
            } else {
                cntHashMap.put(num, 1);
            }

            if (cntHashMap.get(num) > maxCount) {
                maxElement = num;
                maxCount = cntHashMap.get(num);
            }
        }

        return maxElement;
    }
}
This post is licensed under CC BY 4.0 by the author.