Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
acm thang
import java.util.HashMap;
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
HashMap<Integer, ArrayList<Integer>> map2 = new HashMap<Integer, ArrayList<Integer>>();
for (int i : nums) {
if (map.containsKey(i)) {
map.put(i, map.get(i) + 1);
} else {
map.put(i, 1);
}
}
for (Map.Entry<Integer, Integer> kv : map.entrySet()) {
if (map2.containsKey(kv.getValue())) {
ArrayList<Integer> tmp = new ArrayList<Integer>(map2.get(kv.getValue()));
tmp.add(kv.getKey());
map2.put(kv.getValue(), tmp);
} else {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(kv.getKey());
map2.put(kv.getValue(), tmp);
}
}
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = nums.length; i >= 0; i--) {
System.out.println(i);
if (list.size() >= k) {
break;
}
if (!map2.containsKey(i)) {
continue;
}
list.addAll(map2.get(i));
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.