Find k most repeating elements

Given a list and a number k, print out the top k most repeating elements in the list.


1. Use hashmap to store the pair of number and count.

2. Use priority queue to store the hash node based on the value of each hash node, using comparator to define the priority queue.

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

/*
 * To execute Java, please define "static void main" on a class
 * named Solution.
 *
 * If you need more classes, simply define them inline.
 */

public class Solution {
    

  public static void findKElements(List<Integer> list, int k) {

    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

    for (int i = 0; i < list.size(); i++) {
      if (map.containsKey(list.get(i))) {
        map.put(list.get(i), map.get(list.get(i)) + 1);
      }

      else
        map.put(list.get(i), 1);

    }

    Comparator<Entry<Integer, Integer>> cmp;
    cmp = new Comparator<Entry<Integer, Integer>>() {

      @Override
      public int compare(Entry<Integer, Integer> e1, Entry<Integer, Integer> e2) {
        
        return e2.getValue() - e1.getValue();
      }
    };
    
    Queue<Entry<Integer, Integer>> pq = new PriorityQueue<Entry<Integer, Integer>>(map.size(), cmp);

    Iterator<Entry<Integer, Integer>> it = map.entrySet().iterator();

    while (it.hasNext()) {
      pq.offer(it.next());
    }
    
    
    for (int i = 0; i < k; i++) {
      System.out.println(pq.poll().getKey());
    }

  }
  
  public static void main(String[] args) {

    List<Integer> list = new ArrayList<Integer>();
    list.add(0);
    list.add(0);
    list.add(0);
    list.add(1);
    list.add(1);
    list.add(1);
    list.add(1);
    list.add(2);
    list.add(2);
    
    findKElements(list, 2);
  }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值