leetcode347:Top K Frequent Elements

版权声明:文章为作者原创,若要转载请获得作者同意。尊重版权,从你我做起! https://blog.csdn.net/qq_37768971/article/details/88565931

一、题目要求:
347. 前K个高频元素

给定一个非空的整数数组,返回其中出现频率前 高的元素。

示例 1:

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

示例 2:

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

说明:

  • 你可以假设给定的 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log n) , 是数组的大小。

二、简单分析

1.本题可以基于映射(map)实现对不同数据出现频次的存储;

2.将前K个优先级较高的元素存入优先队列,其他元素则出队;

3.将优先队列中k个元素的数据存入LinkedlList中,提交给leetcode,即可完成任务!

三、代码实现

1.具体代码

package IMUHERO;
/// 347. Top K Frequent Elements
/// https://leetcode.com/problems/top-k-frequent-elements/description/
import java.util.*;

public class Solution2 {

    private class Freq{
        public int e,freq;
        public Freq(int e ,int freq){
            this.e=e;
            this.freq=freq;
        }
    }

    private class FreqComparetor implements Comparator<Freq>{
        @Override
        public int compare(Freq a,Freq b){
                return a.freq-b.freq;
        }
    }

    public List<Integer> topKFrequent(int[] nums, int k) {
        TreeMap<Integer,Integer> map=new TreeMap<>();
        for (int num:nums){
            if (map.containsKey(num)){
                map.put(num,map.get(num)+1);
            }
            else{
                map.put(num,1);
            }
        }

        PriorityQueue<Freq> pQ=new PriorityQueue<>(new FreqComparetor());
        for (int key:map.keySet()){
            if (pQ.size()<k){
                pQ.add(new Freq(key,map.get(key)));
            }
            else if (map.get(key)>pQ.peek().freq){
                pQ.remove();
                pQ.add(new Freq(key,map.get(key)));
            }
        }

        LinkedList<Integer> res=new LinkedList<>();
        while (!pQ.isEmpty()){
            res.add(pQ.remove().e);
        }
        return res;

    }

   
}

2.测试代码:

 private static void printList(List<Integer> nums){
        for(Integer num: nums)
            System.out.print(num + " ");
        System.out.println();
    }

    public static void main(String[] args) {

        int[] nums = {1, 1, 1, 2, 2, 3};
        int k = 2;
        printList((new Solution2()).topKFrequent(nums, k));
    }

3.结果:

2 1 


四、提交具体代码到leecode:

成功 显示详情 

执行用时 : 71 ms, 在Top K Frequent Elements的Java提交中击败了29.61% 的用户

内存消耗 : 47.3 MB, 在Top K Frequent Elements的Java提交中击败了2.36%的用户

进行下一个挑战:

猜你喜欢

转载自blog.csdn.net/qq_37768971/article/details/88565931