Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is the text editor interface.
- // Anything you type or change here will be seen by the other person in real time.
- // given an array, return the Kth most frequent item
- // [1,2,3,3], K = 1, return 3; K = 2, return 1 or 2
- import java.util.*;
- class kthMostFrequent {
- static int findMostFrequent(int[] arr, int k) {
- Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
- --k;
- for (int i = 0; i < arr.length; i++) {
- if (!hm.containsKey(arr[i])) {
- hm.put(arr[i], 1);
- }
- else {
- hm.put(arr[i], hm.get(arr[i]) + 1);
- }
- }
- List<MapObject> al = new ArrayList<MapObject>();
- for (Map.Entry<Integer, Integer> entry : hm.entrySet()) {
- int value = entry.getValue();
- int key = entry.getKey();
- MapObject obj = new MapObject(key, value);
- al.add(obj);
- }
- Collections.sort(al, new ObjectComparator());
- return al.get(k).getKey();
- }
- public static void main(String[] args) {
- int[] arr = {1, 2, 3, 3};
- System.out.println(findMostFrequent(arr, 1));
- }
- }
- class MapObject {
- private int key;
- private int value;
- public MapObject(int key, int value) {
- this.value = value;
- this.key = key;
- }
- public int getKey() {
- return key;
- }
- public int getValue() {
- return value;
- }
- // @Override
- // public int compareTo(MapObject o1) {
- // if (this.value < o1.value)
- // return -1;
- // if (this.value == o1.value)
- // return 0;
- // return 1;
- // }
- }
- class ObjectComparator implements Comparator<MapObject> {
- @Override
- public int compare(MapObject o1, MapObject o2) {
- if (o1.getValue() < o2.getValue())
- return 1;
- if (o1.getValue() == o2.getValue())
- return 0;
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment