Java 8 Solution


  • 0
    public class Solution {
        public int majorityElement(int[] nums) {
           
            Map<Integer,Integer> freqTable = Arrays.stream(nums).boxed().collect(Collectors.groupingBy(e -> e, Collectors.reducing(0, e -> 1, Integer::sum)));
                                            
            int maxValueInfreqTable  = Collections.max(freqTable.values());
            
            for(Map.Entry <Integer, Integer> m: freqTable.entrySet()){
                if(m.getValue().equals(maxValueInfreqTable)) return m.getKey();
            }                       
            return -1;
      }
                
        }
    }

Log in to reply
 

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