Java中有TreeSet数据结构,该结构可获取1个最大元素。我需要允许收集N个最大元素的数据结构。
我需要这样的东西:
GreatestN<Integer> greatest = new GreatestN<>(Arrays.asList(5, 2, 1, 7));
greatest.getN(2); // returns {1, 2}
greatest.getN(3); // returns {1, 2, 5}
greatest.add(0);
greatest.getN(2); // returns {0, 1}
最佳答案
您可以对列表进行排序,然后传递索引值以获取最大数量。
List<Integer> greatest = Arrays.asList(5, 2, 1, 7);
Collections.sort(greatest); // By default sorts ascending
System.out.println(greatest.get(greatest.size()-1)); //will give you greatest element in the list.
//System.out.println(greatest.get(greatest.size()-1-nthNumber));
System.out.println(greatest.get(0));//will give you lowest element in the list.