当前位置:首页 > 未命名 > 正文内容

出现频率最高的前 K 个元素

淙嶙7年前 (2018-07-25)未命名593
描述 有一个不为空且仅包含正整数的数组,找出其中出现频率最高的前 K 个数,时间复杂度必须在 O(n log n) 以内。 输入 一行数据包括两部分,一个正整数数组(数字间 ',' 分隔)和一个正整数 K (1 ≤ K ≤ 数组长度),数组和 K 之间有一个空格。 输出 输出包含前 K 个出现频率最高的数,用 ', ' 分隔,保证升序排列。 输入样例 1,1,1,2,2,3 2 输出样例 1,2
private static String solution(String line) {
    // 在此处理单行数据
    String a[] = line.split(" ");
    String[] arr = a[0].split(",");
    int limit = Integer.parseInt(a[1]);
    List<Entity> list = new ArrayList<Entity>();
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    for(int i=0;i<arr.length;i++){
        int key = Integer.parseInt(arr[i]);
        if(map.containsKey(key)){
            map.put(key, map.get(key)+1);
        }else{
            map.put(key, 1);
        }
    }
    for(Integer key : map.keySet()){
        Entity e = new Entity();
        e.setKey(key);
        e.setValue(map.get(key));
        list.add(e);
    }
    Collections.sort(list, new Comparator<Entity>(){
        @Override
        public int compare(Entity o1, Entity o2) {
            return o2.getValue().compareTo(o1.getValue());
        }
    });
    int[] count = new int[limit];
    for(int i =0;i<limit;i++){
        Entity e = list.get(i);
        count[i] = e.getKey();
    }
    Arrays.sort(count);
    StringBuilder res = new StringBuilder();
    for(int i=0;i<count.length;i++){
        res.append(count[i]).append(",");
    }
    return res.substring(0, res.length()-1);
}
static class Entity{
    Integer key;
    Integer value;
    public Integer getKey() {
        return key;
    }
    public void setKey(Integer key) {
        this.key = key;
    }
    public Integer getValue() {
        return value;
    }
    public void setValue(Integer value) {
        this.value = value;
    }
}

相关文章

找出可能的合的组合

找出可能的合的组合

描述 给出一组不重复的正整数,从这组数中找出所有可能的组合使其加合等于一个目标正整数 N,如:一组数为 1, 2, 3,目标数为 4,那么可能的加合组合为:1, 1, 1, 11, 1, 21,...

交叉队列

交叉队列

描述 给出三个队列 s1,s2,s3 ,判断 s3 是否是由 s1 和 s2 交叉得来。如:s1 为 aabcc , s2 为 dbbca。当 s3 为 aadbbcbcac 时,返回 true...

EXPLAIN 命令详解

EXPLAIN 命令详解

在工作中,我们用于捕捉性能问题最常用的就是打开慢查询,定位执行效率差的SQL,那么当我们定位到一个SQL以后还不算完事,我们还需要知道该SQL的执行计划,比如是全表扫描,还是索引扫描,这些都需要...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。