Return the two largest integers in an array of val

2020-02-06 03:29发布

I am attempting to return the two largest integers from my int array. I am able to return the largest and the smallest fine, but I cannot get my algorithm to return the two largest. Any help is greatly appreciated here.

Please forgive any errors in my code. This is a practice session and the question has been taken from last years exam material at university.

Here is my code:

public class TwoLargestIntsArray {

public static void main(String [] args){

    int [] values = new int[5];

    values[0] = 5;
    values[1] = 10;
    values[2] = 15;
    values[3] = 20;
    values[4] = 25;

    System.out.println(twoLargest(values));
    System.out.println();

}

public static int twoLargest(int values[]){

    int largestA = values[0];
    int largestB = values[0];

    for(int i = 0; i < values.length; i++){

            if(values[i] > largestA){
                largestA = values[i];
            }
            if(values[i] < largestA){
                largestB = values[i];   
            }

    }
    return largestA + largestB; 
}

}

标签: java arrays
16条回答
干净又极端
2楼-- · 2020-02-06 04:05

Answer by @Nilesh Jadav covers all cases. Answer by @Peter Lawrey fails in cases where the array has largest value is the last element. for example [10,2,5,1,8,20] returns 20 and 8 with the accepted solution.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-06 04:06

You cannot have a single function return 2 values. You either have to wrap them in an array, or use reference parameters.

查看更多
地球回转人心会变
4楼-- · 2020-02-06 04:07

You can also use nested class to store results of your computing. For example:

  private static class Result {

    int largestA;
    int largestB;

    Result(int largestA, int largestB) {
        this.largestA = largestA;
        this.largestB = largestB;
    }
}

And then receive data something like:

Result result = twoLargest(values);
System.out.println(result.largestA);
System.out.println(result.largestB);
查看更多
神经病院院长
5楼-- · 2020-02-06 04:08
private static void printTwoMaxNumberWithoutSortMethod(int[] input) {
    int max=0,lastMax=0;
    lastMax=input[0];
    max=input[0];
    for(int i=1;i<input.length;i++)
    {
        if(lastMax<input[i] & max<input[i])
        {
            lastMax=max;
            max=input[i];

        }
    }
    System.out.println("lastMax="+lastMax+" : max="+max);

}
查看更多
登录 后发表回答