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

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

淙嶙8年前 (2018-07-25)未命名762
描述 有一个不为空且仅包含正整数的数组,找出其中出现频率最高的前 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;
    }
}

相关文章

移除 K 位得到最小值

移除 K 位得到最小值

描述 有一行由正数组成的数字字符串,移除其中的 K 个数,使剩下的数字是所有可能中最小的。假设: 字符串的长度一定大于等于 K 字符串不会以 0 开头 输入 一行由正整数组成的数字字...

maven 常用命令汇总

maven 常用命令汇总

1. 编译源代码: mvn compile 2. 编译测试代码: mvn test-compile 3. 运行测试: mvn test 4. 产生site:...

dubbo XML配置(三)

dubbo XML配置(三)

配置之间的关系标签用途解释<dubbo:service/>服务配置用于暴露一个服务,定义服务的元信息,一个服务可以用多个协议暴露,一个服务也可以注册到多个注册中心<dubbo:ref...

发表评论

访客

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