Top K Frequent Elements

题目链接

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;

public class Solution {

    public static void main(String args[])
    {
        Solution obj=new Solution();
        List<Integer> result=obj.topKFrequent(new int[]{1,1,1,2,2,3},2);
        for (Integer integer : result) {
            System.out.println(integer);
        }
    }

    public List<Integer> topKFrequent(int[] nums, int k) {
        Arrays.sort(nums);
        PriorityQueue<Record> heap=new PriorityQueue<Record>();
        int last=nums[0];
        int count=0;
        for(int i=0;i<nums.length;i++)
        {
            if(last!=nums[i])
            {
                heap.add(new Record(last, count));
                count=1;
                last=nums[i];
            }
            else
            {
                count++;
            }
        }
        heap.add(new Record(last, count));
        List<Integer> result=new LinkedList<Integer>();
        for(int i=0;i<k;i++)
        {
            result.add(heap.poll().nums);
        }
        return result;
    }
}

class Record implements Comparable<Record>
{
    int nums;
    int count;
    Record(int nums,int count)
    {
        this.nums=nums;
        this.count=count;
    }
    @Override
    public int compareTo(Record o) {

        return count<o.count?1:-1;
    }
}



你可能感兴趣的:(Top K Frequent Elements)