查找数组Java中的最小和第二小值

时间:2014-10-22 02:55:15

标签: java arrays

我试图创建两个找到最小值的方法1和一个在对象数组中找到第二个最小值的方法。

我已经像这样写了两个

public static BanffMarathonRunner getFastestTime(BanffMarathonRunner[] runner){
    if(runner.length == 0){
        return null;
    }
    BanffMarathonRunner fastest = runner[0];
    for(int i = 0; i< runner.length; i++){
        BanffMarathonRunner now = runner[i];
        if(now.Time < fastest.Time){
            fastest = now;

        }
    }
    return fastest;
}
    public static BanffMarathonRunner getSecondFastestTime(BanffMarathonRunner[] runner){
        if(runner.length == 0){
            return null;
        }
        BanffMarathonRunner fastest = runner[0];
        BanffMarathonRunner secondFastest = runner[0];
        for(int i = 0; i< runner.length; i++){
            BanffMarathonRunner now = runner[i];
            if(now.Time < fastest.Time){
                fastest = now;
        for(int j = 0; j< runner.length; j++){
            BanffMarathonRunner now2 = runner[j];
            if(now2.Time < secondFastest.Time){

                secondFastest = now2;
                if(now2.Time == fastest.Time){
                    secondFastest = secondFastest;
                }
            }
        }

            }
        }
        return secondFastest;
    }

我已经找到了如何找到最小的值,我只需要找到第二个最小值,我不确定如何。

任何想法?谢谢!

3 个答案:

答案 0 :(得分:1)

Arrays.sort(test);
   if(test.length-2 >= 0)
       System.out.println(test[test.length-2]);

答案 1 :(得分:0)

一旦您知道最快的跑步者,请存储此条目的索引。然后当找到第二快的跑步者时,使用'continue'

忽略循环中最快跑步者的指数

同样对于任何K最小的条目,您可以看到关于这个问题的想法:K smallest in Array Java

答案 2 :(得分:0)

类似的东西:

findSecondSmallest anArray[]:
    if anArray.length < 2:
        return null;
    fastest = anArray[0];
    secondFastest = anArray[1];
    if fastest > secondFastest:
        fastest = anArray[1];
        secondFastest = anArray[0]
    for each element in anArray:
        if element < fastest:
            secondFastest = fastest;
            fastest = element;
        else if element < secondFastest:
            secondFastest = element;

    return secondFastest