考虑每一项与整数字段相关联的项的对象列表:
Item[0]->1
Item[1]->4
Item[2]->2
Item[3]->9
Item[4]->1
Item[5]->9
Item[6]->3
Item[7]->6
Item[8]->7
Item[9]->9我想筛选出一个具有最大值的项目的列表。在这种情况下,由于最大数目是9,我将收到{Item[3],Item[5],Item[9]}。我这样做的方法是先迭代整个列表,然后在某个地方存储最大值(9),然后再迭代一次,并将其字段等于9的项添加到新列表中。
但是每次我想做类似的事情时,这都是大量的代码,而且看起来效率不高。是否有更好的方法(无论是在效率方面还是在整洁方面)?
发布于 2014-12-19 16:13:57
我可能会一次选一次。
就像这个伪码:
int max = Integer.MIN_VALUE;
Set<Item> maxItems = new LinkedHashSet<>();
for( Item item : items ) {
//if the item has a greater value clear the set and set the new max value
if( item.value > max ) {
maxItems.clear();
max = item.value;
}
//due to the code above value should always be <= max here, so we just need to check ==
if( item.value == max ) {
maxItems.add( item );
}
}发布于 2014-12-19 16:15:52
我想你可以这样做
List<Integer> maxValues = new ArrayList<Integer>();
int max = Integer.MIN_VALUE;
for(int i = 0; i < item.length; i++) {
if(item[i] > max) {
max = item[i];
maxValues = new ArrayList<Integer>();
}
if(item[i] == max) {
maxValues.add(i);
}
}发布于 2014-12-19 16:21:16
最简单的方法是使用一个包含数字和索引列表的Map。
Map<int number, List<int index> >迭代列表,更新最大值&存储其索引。
->如果再次满足相同的最大值,也将其索引添加到列表中。
->如果发现了新的最大值,请更新地图中的数字。
https://stackoverflow.com/questions/27569735
复制相似问题