Java HashMap solution


  • 0
    M
    public static int majorityElement(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        
        for (int i : nums) {
            if (!map.containsKey(i)) {
                map.put(i, 1);
            }
            else {
                map.put(i, map.get(i) + 1);
            }
        }
        
        int key = nums[0];
        int value = map.get(nums[0]);
        
        for (int i = 1; i < nums.length; i++) {
            if (map.get(nums[i]) > value) {
                value = map.get(nums[i]);
                key = nums[i];
            }
        }
        return key;
    }

Log in to reply
 

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