Guest User

Untitled

a guest
Jan 9th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. // This is the text editor interface.
  2. // Anything you type or change here will be seen by the other person in real time.
  3.  
  4. // given an array, return the Kth most frequent item
  5. // [1,2,3,3], K = 1, return 3; K = 2, return 1 or 2
  6. import java.util.*;
  7. class kthMostFrequent {
  8.  
  9.  
  10.  
  11. static int findMostFrequent(int[] arr, int k) {
  12. Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
  13. --k;
  14. for (int i = 0; i < arr.length; i++) {
  15. if (!hm.containsKey(arr[i])) {
  16. hm.put(arr[i], 1);
  17. }
  18. else {
  19. hm.put(arr[i], hm.get(arr[i]) + 1);
  20. }
  21. }
  22.  
  23. List<MapObject> al = new ArrayList<MapObject>();
  24.  
  25. for (Map.Entry<Integer, Integer> entry : hm.entrySet()) {
  26. int value = entry.getValue();
  27. int key = entry.getKey();
  28. MapObject obj = new MapObject(key, value);
  29. al.add(obj);
  30.  
  31. }
  32. Collections.sort(al, new ObjectComparator());
  33.  
  34. return al.get(k).getKey();
  35. }
  36.  
  37. public static void main(String[] args) {
  38. int[] arr = {1, 2, 3, 3};
  39.  
  40. System.out.println(findMostFrequent(arr, 1));
  41. }
  42. }
  43.  
  44. class MapObject {
  45. private int key;
  46. private int value;
  47.  
  48.  
  49. public MapObject(int key, int value) {
  50. this.value = value;
  51. this.key = key;
  52. }
  53. public int getKey() {
  54. return key;
  55. }
  56. public int getValue() {
  57. return value;
  58. }
  59. // @Override
  60. // public int compareTo(MapObject o1) {
  61. // if (this.value < o1.value)
  62. // return -1;
  63. // if (this.value == o1.value)
  64. // return 0;
  65. // return 1;
  66. // }
  67. }
  68. class ObjectComparator implements Comparator<MapObject> {
  69. @Override
  70. public int compare(MapObject o1, MapObject o2) {
  71. if (o1.getValue() < o2.getValue())
  72. return 1;
  73. if (o1.getValue() == o2.getValue())
  74. return 0;
  75. return -1;
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment