Top K Frequent Elements

本文介绍了一种使用Java实现的算法,该算法通过排序和优先队列来找出数组中出现频率最高的k个元素。文章提供了完整的代码示例,包括主函数测试案例以及自定义的记录类用于比较元素频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值