Java solution using HashMap and Comparator


  • 0
    S
    public class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            HashMap<Integer,Integer> map = new HashMap<>();
            for(int i:nums)
            {
                if(!map.containsKey(i))
                {
                    map.put(i,1);
                }
                else
                {
                    int count = map.get(i);
                    map.put(i,count+1);
                }
            }
            List<Point> listpoints = new ArrayList<>();
            for(Map.Entry<Integer,Integer> i : map.entrySet())
            {
                Point point = new Point(i.getKey(),i.getValue());
                listpoints.add(point);
            }
            Collections.sort(listpoints);
            List<Integer> list = new ArrayList<>();
            for(int i = 0;i<k;i++)
            {
                int temp = (listpoints.get(i)).key;
                list.add(temp);
            }
            return list;
            
            
          
        }
        
        class Point implements Comparable<Point>
        {
            public int key,value;
            public Point(int a,int b)
            {
                key = a; value = b;
            }
            public int compareTo(Point point)
            {
                if(this.value > point.value)
                {
                    return -1;
                }
                else if(this.value < point.value)
                {
                    return 1;
                }
                else return 0;
            }
            
        }
        
    }
    

Log in to reply
 

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