Finding the n largest values in a hashmap
本问题已经有最佳答案,请猛点这里访问。
我有一个包含
1 2 3 | ("a",2) ("ab", 3) ("c",5) etc.. |
我看到过一些问题,它们在哪里找到单个最大值并将其存储在另一个哈希图中,但是我如何能够循环这个值,以便找到"n"最大的数字并将其放入结果哈希图中呢?
例如,对于上面的hashmap条目,如果n为2,则会找到2个最大值并放入结果hashmap中。
1 2 | ("ab", 3) ("c", 5) |
非常感谢你的预告。
也许这不是最有效的方法,但它可以解决您的问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | static HashMap<String, Integer> nLargest(HashMap<String, Integer> map, int n) { //map and n largest values to search for Integer value; ArrayList<String> keys = new ArrayList<>(n); //to store keys of the n largest values ArrayList<Integer> values = new ArrayList<>(n); //to store n largest values (same index as keys) int index; for (String key : map.keySet()) { //iterate on all the keys (i.e. on all the values) value = map.get(key); //get the corresponding value index = keys.size() - 1; //initialize to search the right place to insert (in a sorted order) current value within the n largest values while (index >= 0 && value > values.get(index)) { //we traverse the array of largest values from smallest to biggest index--; //until we found the right place to insert the current value } index = index + 1; //adapt the index (come back by one) values.add(index, value); //insert the current value in the right place keys.add(index, key); //and also the corresponding key if (values.size() > n) { //if we have already found enough number of largest values values.remove(n); //we remove the last largest value (i.e. the smallest within the largest) keys.remove(n); //actually we store at most n+1 largest values and therefore we can discard just the last one (smallest) } } HashMap<String, Integer> result = new HashMap<>(values.size()); for (int i = 0; i < values.size(); i++) { //copy keys and value into an HashMap result.put(keys.get(i), values.get(i)); } return result; } |
我希望这对你有帮助。