查找列表的最大年龄元素的最佳方法 [英] best way to find maximum age element of List

查看:127
本文介绍了查找列表的最大年龄元素的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<Man> list=new ArrayList<Man>();

Man manA = new Man(29);  // constructor parameter is age, use manA.age to get 29
list.add(manA);
Man manB = new Man(23);
list.add(manB);
Man manC = new Man(42);
list.add(manC);
Man manD = new Man(38);
list.add(manD);

我想获得list中的最大年龄元素manC

I want get the maximum age element manC in list,

什么是最好的(最快的)方法?

What's the best(fastest) way to do this?

推荐答案

无论如何,除非您使用列表以外的其他方法,否则您将必须在O(N)时间内完成该操作.

No matter what, you're going to have to do it in O(N) time unless you use something other than a list.

Man maxAge = new Man(0);
for(Man man : list) {
  if(man.age > maxAge.age) {
    maxAge = man;
  }
}

这将简单地遍历整个列表,记录该年龄的男性.循环结束后,maxAge将是其中最早的一个.

This will simply go through the entire list, recording the man with the greatest age it has encountered yet. When the loop is finished, maxAge will be the oldest of them all.

为回应您有关Collections.max的更好"的评论,我以为我只包含了此注释,所以没有人感到困惑.从某种意义上说,比较器的连接是一种很好的做法,并且它是java.util的一部分这一事实也更好.但是,如果您查看源代码(如下所示),它的作用完全相同.因此,从算法上讲,它并不好(如上所述,速度更快).

In response to your comment about Collections.max being "better", I thought I'd just include this note just so no one is confused. It is better in the sense that interfacing a comparator is good practice and the fact that it is part of java.util is nice too. However, if you look at the source code (attached below) it does exactly the same thing. So algorithmically, it is not better (faster, as you mentioned above).

public static <T extends Object & Comparable<? super T>> T max(
  Collection<? extends T> collection) {
  Iterator<? extends T> it = collection.iterator();
  T max = it.next();
  while (it.hasNext()) {
    T next = it.next();
    if (max.compareTo(next) < 0) {
      max = next;
    }
  }
  return max;
}

这篇关于查找列表的最大年龄元素的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆