简体   繁体   English

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

[英]Finding the smallest and second smallest value in an array Java

I'm trying to create two method one that finds the smallest and one that finds the second smallest value in an Array of objects. 我正在尝试创建两种方法,一种找到对象数组中的最小值,另一种找到对象数组中第二个最小值。

I've written the two like this 我已经这样写了两个

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;
    }

I've figured out the how to find the smallest value, I just need to find the second smallest and I'm not sure how. 我已经找到了如何找到最小的值,我只需要找到第二个最小的值,我不确定怎么做。

Any Ideas? 有任何想法吗? Thanks! 谢谢!

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

Once you know the fastest runner, store the index of this entry. 一旦知道最快的跑步者,就存储该条目的索引。 Then when finding the 2nd fastest runner, ignore the index of Fastest runner in the loop using 'continue' 然后,在找到第二快跑者时,使用“ continue”忽略循环中最快跑者的索引

Also for any K-smallest entry, you can see the idea given on this question: K smallest in Array Java 同样,对于任何K最小的条目,您都可以看到此问题给出的想法: Array Java中的K最小

something like this: 像这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM