347.前 K 个高频元素

使用map和sort

class Dual{
    int key;
    int value;
    Dual(int key,int value){
        this.key=key;
        this.value=value;
    }
}
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], 0);
                res++;
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }
        Dual[] array = new Dual[res];
        int idx=0;
        for(Map.Entry<Integer, Integer> entry:map.entrySet()){
            array[idx++]= new Dual(entry.getKey(),entry.getValue());
        }
        Arrays.sort(array,(d1,d2)->Integer.compare(d2.value,d1.value));
        int[] result = new int[k];
        for(int i=0;i<k;i++){
            result[i]=array[i].key;
        }
        return result;
    }
}

首先用map记录每个value出现的频次key,然后倒入数组中,以key进行sort排序,然后再返回前k个value

使用小顶堆

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], 0);
                res++;
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }
        PriorityQueue<int[]> pq = new PriorityQueue<>((pair1, pair2) -> pair1[1] - pair2[1]);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (pq.size() < k) {
                pq.offer(new int[] { entry.getKey(), entry.getValue() });
            } else {
                if (entry.getValue() > pq.peek()[1]) {
                    pq.poll();
                    pq.offer(new int[] { entry.getKey(), entry.getValue() });
                }
            }
        }
        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = pq.poll()[0];
        }
        return result;
    }
}

你可能感兴趣的:(java,算法,数据结构)