zoukankan      html  css  js  c++  java
  • LeetCode

    Given a non-empty array of integers, return the k most frequent elements.

    Example 1:

    Input: nums = [1,1,1,2,2,3], k = 2
    Output: [1,2]
    

    Example 2:

    Input: nums = [1], k = 1
    Output: [1]

    Note:

    • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
    • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

    找数组中,频率topk。

    要求时间复杂度小于O(n log n),桶排序或者堆

    桶排序:

    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            if (nums == null || nums.length <= 0 || k <= 0)
                return new ArrayList<Integer>();
            int len = nums.length;
            Map<Integer, Integer> dict = new HashMap<Integer, Integer>();
            for (int i=0; i<len; i++) {
                if (dict.containsKey(nums[i])) {
                    dict.put(nums[i], dict.get(nums[i])+1);
                } else {
                    dict.put(nums[i], 1);
                }
            }
            List<List<Integer>> bucket = new ArrayList<>(len);
            for (int i=0; i<len; i++) {
                bucket.add(new ArrayList<Integer>());
            }
            int max = 0;
            for (Map.Entry<Integer, Integer> entry: dict.entrySet()) {
                int num = entry.getKey();
                int cnt = entry.getValue();
                if (cnt > max)
                    max = cnt;
                bucket.get(cnt-1).add(num);
            }
            List<Integer> ret = new ArrayList<Integer>();
            for (int i=max-1; i>=0; i--) {
                List<Integer> temp = bucket.get(i);
                for (int j=0; j<temp.size(); j++) {
                    ret.add(temp.get(j));
                    if (ret.size() == k)
                        return ret;
                }
            }
            return ret;
        }
    }
  • 相关阅读:
    又见Alice and Bob
    算法7-6:图的遍历——广度优先搜索
    算法7-5:图的遍历——深度优先搜索
    水池数目
    过河问题
    括号配对问题
    C# 客户端判断是否安装office03、07或WPS
    C# json
    开源cms
    可执行代码(Executable Code)目标代码(object code)
  • 原文地址:https://www.cnblogs.com/wxisme/p/9719660.html
Copyright © 2011-2022 走看看