不会就坚持56天吧 频率最高

 堆排序

class Solution {
    public class Node{
        int val;
        int cnt;
        Node(int val, int cnt) {
            this.val = val;
            this.cnt = cnt;
        }
    }
    public int[] topKFrequent(int[] nums, int k) {
        PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> o1.cnt - o2.cnt);
        Arrays.sort(nums);
        for(int i = 0, j = 0; j < nums.length; i = j) {
            while (j < nums.length && nums[i] == nums[j]) {
                j++;
            }
            Node node = new Node(nums[i], j - i);
            System.out.println(node.val + " " + node.cnt);
            pq.add(node);
            if(pq.size() > k) {
                pq.poll();
            }
        }
        int[] ans = new int[k];
        int cnt = 0;
        while(!pq.isEmpty()) {
            ans[cnt++] = pq.poll().val;
        }
        return ans;
    }
}

快排

 

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        // 统计数字出现次数
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; ++i) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }

        // 记录数字以及出现的次数
        List<int[]> values = new ArrayList<int[]>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            values.add(new int[]{entry.getKey(), entry.getValue()});
        }

        int[] ans = new int[k];
        quickSort(values, k - 1, 0, values.size() - 1, ans, 0);
        return ans;
    }
    public void quickSort(List<int[]> values, int k, int start, int end, int[] ans, int index) {
        // 将第一个点作为分割点
        int[] num = values.get(start);
        int i = start;
        int j = end;
        while(i < j) {
            // 移动右指针
            while (i < j && values.get(j)[1] < num[1]) {
                j--;
            }
            Collections.swap(values, i, j);
            // 移动左指针
            while (i < j && values.get(i)[1] >= num[1]) {
                i++;
            }
            Collections.swap(values, i, j);
        }

        // 如果前k个在分隔点左侧
        if(k < i) {
            quickSort(values, k, start, i - 1, ans, index);

        // 如果第k个刚好在分隔点,或在分割点右侧
        } else {
            for(int x = start; x <= i; ++x) {
                ans[index++] = values.get(x)[0];
            }
            // 如果前k个在分隔点右侧
            if(k > i) {
                quickSort(values, k, i + 1, end, ans, index);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值