【问题标题】:Java: grabbing second highest [duplicate]Java:获得第二高[重复]
【发布时间】:2011-09-01 22:13:49
【问题描述】:

可能重复:
Finding the second highest number in array

我有这个,

       for(int i=0;i<Dices.length;i++){
        if( Dices[i].getValue() > highest ){
            highest = Dices[i].getValue();
        }
       }

获得最高价值。我现在想拿到第二高,怎么办?我不能利用这个最高变量来获得第二高吗?

【问题讨论】:

  • 您有定义的最高值吗?为什么你没有定义第二高的值?将它们放在 ArrayList 中按升序排序,循环遍历它们并存储先前的值。
  • 你有一个die和一些dice而不是dices

标签: java


【解决方案1】:
  • Sort the array 使用自定义 Comparator (make a copy of the array 如果您无法对原件进行排序)
  • 选择已排序数组的最后一项:

    // hopefully you have checked in advance that there is more than one item
    return sortedDices[sortedDices.length-2];
    

【讨论】:

  • 既然我们只讨论最高的两个,您是否必须对整个数组进行排序?我只是想想想你只遍历数组一次的逻辑。我确实同意对数组进行排序是最好的解决方案,只是在这里尝试跳出框框思考。
  • @Ryan 哪个是最好的取决于具体情况。我的是最有用和最易于管理的,Andy 是最有效的(至少对于大型阵列而言)
【解决方案2】:

O(n) 速度下这样的事情怎么样:

// first, second, d0, d1, di all typed by whatever getValue() returns...
// This assumes you have at least two elements in your Dices array

d0 = Dices[0].getValue();
d1 = Dices[1].getValue();
if (d0 > d1) {
    first=d0;
    second=d1;
} else {
    first=d1;
    second=d0;
}

for (int i = 2; i < Dices.length; i++) {
    di = Dices[i].getValue();
    if (di > first) {
        second = first;
        first = di;
    } else if (di > second)
        second = di;
}

【讨论】:

  • @Andy 很棒的解决方案!这正是我在评论@Sean 的回答时正在考虑的事情。
  • @Andy,+1 用于实施正确的解决方案
  • +1 提高效率,尽管您可以说这是过早优化的经典案例。现在请让我们有 3 个最大值:-)
  • @Sean 我懒得回答前三个值。除非我真的需要速度,否则我会使用您的解决方案。
  • @Andy 我并没有认真要求一个,我只是指出了你答案的弱点。但是给定一个包含超过一百万个条目的数组,我也会使用您的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多