搜索数组的最高值,即使是平局

时间:2013-12-02 19:19:01

标签: java arrays

我有两个数组:

String [] nameArr = new String[10];
double [] totalArr = new double[10];

nameArr包含人员姓名,totalArr包含人们在筹款活动中筹集的金额。我想得到筹集最多钱的人的名字。一些伪代码说明:

int winner = array_maximum(totalArr); //would return array element 0-9
//winner = 4 if totalArr[4] has the highest value

所以我可以这样做:

String winPerson = nameArr[winner];
System.out.println(winPerson);

我确信执行此操作的方法不涉及返回数组元素编号,但这只是我认为它可能起作用的一种方式。 Java中是否存在这样的方法来做我想做的事情?如果有平局怎么办?

这是我做过的一些粗略工作,仍然在测试:

private String winner() {
    int i;
    double tentativeMaximum = totalArr[0];
    String winningPersons = nameArr[0];
    for (i = 1; i < totalArr.length; i++) {
        if (totalArr[i] > tentativeMaximum) {
            winningPersons = nameArr[i];
            tentativeMaximum = totalArr[i];
        } else if (totalArr[i] == tentativeMaximum) {
            winningPersons = winningPersons + " plus " + nameArr[i];
        }
    }
    winningPersons = winningPersons + " has won";
    return winningPersons;
}

3 个答案:

答案 0 :(得分:2)

如果您想要所有与筹集的最大资金相对应的名称,您应该设计方法以始终返回列表。这是一种可能性:

List<String> bestFundraisers(String[] names, double[] totals) {
    final List<String> winners = new ArrayList<>();
    final int n = names.length;
    // optional: throw an exception if totals.length != n
    double max = Double.NEGATIVE_INFINITY;
    for (int i = 0; i < n; ++i) {
        double raised = totals[i];
        if (raised >= max) [
            if (raised > max) {
                winners.clear();
                max = raised;
            }
            winners.add(names[i]);
        }
    }
    return winners;
}

答案 1 :(得分:2)

对于这样一个小型数组,最简单的解决方案是找到最大值并获取所有最大值。这不会创建任何对象。

public static void printBestFundraisers(String[] names, double[] totals) {
    double max = totals[0];
    for(double d: totals) 
        if(max < d)
            max = d;
    for(int i = 0; i < names.length; i++)
        if(totals[i] == max)
            System.out.println(names[i]);
}

答案 2 :(得分:-1)

我建议先创建一个名为Person的类。每个人都持有一个字符串,名称和数字,他们的资金。在另一个类中创建一种向所有人输入所有信息的方法。创建一个人员数组并按分数对其进行排序。使用高分的人并返回他们的名字。