Java solution counting frequency


  • 0
    M

    Counting the frequency and populating a HashMap, then going through the Map looking for the entry that is greater than the majority number. Runtime: 30 ms

    public class Solution {
        
        public int majorityElement(int[] nums) {
            int maj = nums.length / 2;
            Map<Integer, Integer> freq = new HashMap<>();
            
            for (int i = 0; i < nums.length; i++) {
                Integer value = freq.get(nums[i]);
                if (value == null) value = new Integer(1);
                else value++;
                freq.put(nums[i], value);
            }
            
            for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
                if (entry.getValue() > maj) return entry.getKey();
            }
            
            return -1;
        }
        
    }
    

Log in to reply
 

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