Simple HashMap Java Solution O(n)


  • 0
    P
    public class Solution {
        public int majorityElement(int[] nums) {
            HashMap<Integer, Integer> hmap = new HashMap<>();
            for(int i = 0; i < nums.length; i++) {
                if(hmap.containsKey(nums[i]))
                    hmap.put(nums[i], hmap.get(nums[i])+1);
                else
                    hmap.put(nums[i], 1);
                if(hmap.get(nums[i]) > Math.floor(nums.length/2))
                    return nums[i];
            }
            return 0;
        }
    }
    

    Put every element from the array into a HashMap until an element occurrence is greater than Math.floor(nums.length / 2) (since this is guaranteed).


  • 0
    E

    Very useful !
    THX


Log in to reply
 

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