HashMap Java Solution O(n)


  • 0
    public int majorityElement(int[] nums) {
            
            int answer = 0;    
            Map<Integer, Integer> map = new HashMap<Integer,Integer>();
            
    /*Check if the element has an associated key: 
    If yes, increment count by 1, otherwise put (val, 1).*/
    
            for (int val : nums){
                Integer count = map.get(val);
                map.put(val, count != null ? count + 1 : 1);
            }
            
    /*Collections.max returns the maximum element of the collection, 
    depending on the natural ordering of its elements.*/
    
            int max = Collections.max(map.values());
            
    //Retrieve key that has associated value = max (majority element)
            for (Map.Entry<Integer, Integer> entry : map.entrySet()){
                if(entry.getValue().equals(max)){
                    answer = entry.getKey();
                }
            }
            
            return answer;
            
        }
    
    

Log in to reply
 

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