【排序22:前 K 个高频元素】(int数组排序)

本文介绍了一种用于查找整数数组中出现频率最高的前k个元素的算法。通过数组排序及频率计数的方法,实现了对输入数组的有效处理。适用于需要快速找出主要元素的应用场景。

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

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:

输入: nums = [1], k = 1
输出: [1]

【解题思路】首先对数组进行排序,找到每一个数出现的频率,设置一个大小为k 的数组,如果评率大于该数组内出现频率最小的数,则替换它。

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        List<Integer> Nums = Arrays.stream(nums).boxed().collect(Collectors.toList());
        Collections.sort(Nums);

        int cnt = 0;
        int num = 99999;
        int[] ans = new int[k];
        int[] ansCnt = new int[k];
        int min = 0;

        for(int i = 0; i < Nums.size(); i++){
            if(Nums.get(i) != num){
                for(int j = 0; j < k; j++){
                    if(ansCnt[j] < ansCnt[min])
                    {
                        min = j;
                    }
                }

                if(num != 99999)
                {
                    if(ansCnt[min] < cnt)
                    {
                        ansCnt[min] = cnt;
                        ans[min] = num;
                    }
                }

                num = Nums.get(i);
                cnt = 1;
            }
            else cnt++;
        }

        for(int j = 0; j < k; j++){
            if(ansCnt[j] < ansCnt[min])
            {
                min = j;
            }
        }
        if(ansCnt[min] < cnt)
        {
            ansCnt[min] = cnt;
            ans[min] = num;
        }

        return ans;
    }
}

int[]数组排序

首先将int[]数组转换为List,再使用Collections.sort()方法对list排序

//方法一:Collections.sort()
int[] nums = {3,0,1,0};
List<Integer> Nums = Arrays.stream(nums).boxed().collect(Collectors.toList());
Collections.sort(Nums);
//方法二:Arrays.sort()
int[] nums = {1,2,3,4}
Arrays.sort(nums);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值