Java: N/3 Repeat Number: Simple solution with map


#1

Below is my simple solution to find N/3 Repeat number in a List.
I have used a map to store the repeat count 1st.
then checking if any number is present for more then N/3 times (where N is the size of the list).

    public class Solution {
    // DO NOT MODIFY THE LIST
    public int repeatedNumber(final List<Integer> a) {
        
        Map<Integer, Integer> map = new HashMap<>();
        
        int limit = Math.round(a.size()/3);
        
        for(Integer i : a){
            if(map.containsKey(i)){
                map.put(i, (map.get(i)+1));
            }else{
                map.put(i, 1);
            }
        }
        
        for(Map.Entry<Integer, Integer> e : map.entrySet()){
            if(e.getValue() > limit){
                return e.getKey();
            }
        }
        
        return -1;
    }
}

#2

Could have completed in a single loop.

        public int repeatedNumber(final List<Integer> a) {
            Map<Integer, Integer> distinct = new HashMap<>();
            int n  = a.size();
            for(Integer in: a) {
                distinct.compute(in, (k, v) -> {
                Integer val = null;
                if(v == null) {
                    val = 1;
               } else {
                    val = v + 1;
               }
               return val;
           });
           Integer output = distinct.get(in);

           if(output > n/3) {
               return in;
           }
       }
       return -1;
     }