44ms Java accepted solution


  • 0
    P

    import java.util.LinkedHashMap;
    public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
    HashMap<Integer, Integer> hp = new HashMap<>();
    for(int i : nums){
    if(hp.get(new Integer(i)) != null)
    hp.put(new Integer(i), hp.get(new Integer(i))+1);
    else
    hp.put(new Integer(i), 1);
    }
    return sortByValues(hp, k);
    }

    private static List<Integer> sortByValues(HashMap map, int k) { 
       List list = new LinkedList(map.entrySet());
        List<Integer> ansList = new ArrayList<>();
       // Defined Custom Comparator here
       Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
               return ((Comparable) ((Map.Entry) (o2)).getValue())
                  .compareTo(((Map.Entry) (o1)).getValue());
            }
       });
    
       // using LinkedHashMap to preserve the insertion order
       HashMap sortedHashMap = new LinkedHashMap();
       int i = k;
       for (Iterator it = list.iterator(); it.hasNext() && i > 0; i--) {
              Map.Entry entry = (Map.Entry) it.next();
              //sortedHashMap.put(entry.getKey(), entry.getValue());
              try{
              ansList.add((int) (entry.getKey()));
              }catch(Exception e){
                  
              }
       } 
       return ansList;
    

    }
    }


Log in to reply
 

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