Skip to content

Instantly share code, notes, and snippets.

@kbohinski
Created September 21, 2016 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbohinski/e42e39b77a0ef58219bb44b3d6525d85 to your computer and use it in GitHub Desktop.
Save kbohinski/e42e39b77a0ef58219bb44b3d6525d85 to your computer and use it in GitHub Desktop.
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