15 ms JAVA Solution, Heap


  • 0
    Y
    public class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            Arrays.sort(nums);
            PriorityQueue<int[]> heap = new PriorityQueue<int[]>(new Comparator<int[]>(){
                public int compare(int[] a, int[] b){
                    return b[1] - a[1];
                }
            });
            List<Integer> list = new ArrayList<Integer>();
            int i = 0;
            while(i < nums.length){
                int flag = nums[i++];
                int[] map = new int[2];
                map[0] = flag;
                map[1] = 1;
                while(i < nums.length && nums[i] == flag){
                    map[1]++;
                    i += 1;
                }
                heap.offer(map);
            }
            for(int j=0; j<k; j++){
                if(!heap.isEmpty()){
                    list.add(heap.poll()[0]);
                }else{
                    break;
                }
            }
            return list;
        }
    }
    

Log in to reply
 

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