My Java Solution Using HashMap (Clear Explanation)


  • 0
    X

    It didn't specify how many majority elements it may have, so I assume as long as it finds the first one, it will be returned.
    HashMap keeps track on the number of appearances for every number in the array. If it was appeared, then increasing the number of appearances; if not, set number of appearances to 1.

    class Solution {
        public int majorityElement(int[] nums) {
            HashMap<Integer, Integer> map = new HashMap(); //from nums to # of appearances
            for (int i = 0; i < nums.length; i++) {
                if (map.containsKey(nums[i])) {
                    map.put(nums[i], map.get(nums[i])+1);
                } else {
                    map.put(nums[i], 1);
                }
                if (map.get(nums[i]) > nums.length/2) return nums[i];
            }
            
            return 0;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.