Java 返回值数组中的两个最大整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16384472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:37:00  来源:igfitidea点击:

Return the two largest integers in an array of values

javaarrays

提问by PrimalScientist

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.

我试图从我的 int 数组中返回两个最大的整数。我能够返回最大和最小的罚款,但我无法让我的算法返回最大的两个。在这里非常感谢任何帮助。

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

}

采纳答案by Peter Lawrey

You can write

你可以写

public static int[] twoLargest(int values[]){
    int largestA = Integer.MIN_VALUE, largestB = Integer.MIN_VALUE;

    for(int value : values) {
        if(value > largestA) {
            largestB = largestA;
            largestA = value;
        } else if (value > largestB) {
            largestB = value;
        }
    }
    return new int[] { largestA, largestB }; 
}

回答by Sagar Waghmare

public static void twoLargest(int values[]){

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

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

            if(values[i] > largestA){
                largestB = largestA;
                largestA = values[i];
            }
            else if (values[i] > largestB && values[i] != largestA) {
                largestB = values[i];
            }
    }
    System.out.println("Largest - " + largestA);
    System.out.println("2nd largest Largest - " + largestB);
}

回答by Niels Keurentjes

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

您不能让单个函数返回 2 个值。您要么必须将它们包装在一个数组中,要么使用引用参数。

回答by Nick

Pass array to be filled with values:

传递要填充值的数组:

public static void twoLargest(int [] values, int [] ret){
    //...
    ret[0] = largestA;
    ret[1] = largestB;
}


int [] ret = new int [2];
twoLargest(values, ret);
// now ret[0] is largestA
// and ret[1] is largestB

回答by Santosh Panda

Try this out:

试试这个:

public static int[] twoLargest(int values[]){

    int[] result = new int[2];
    int largestA = 0;
    int largestB = 0;

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

            if(values[i] > largestA){
            largestB = largestA;
            largestA = values[i];
        }
    }
     result[0] = largestA;
     result[1] = largestB;

    return result; 
}

回答by Juned Ahsan

I am assuming it will help you in case you are able to get the largest, secondlargest, thirdlargest and so on from a function. I have created such a one :

我假设如果您能够从函数中获得最大的、第二大的、第三大的等等,它会对您有所帮助。我创建了这样一个:

public static int xLargest(int values[], int largeIndex)

Just pass the array and the largeIndex, for largest send 1 , for second largest send 2 and so on.

只需传递数组和 largeIndex,对于最大发送 1 ,对于第二大发送 2 等等。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class XLargestIntArray {

    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(xLargest(values,2));
        System.out.println();

    }

    public static int xLargest(int values[], int largeIndex) {

        List<Integer> intList = new ArrayList<Integer>();
        for (int index = 0; index < values.length; index++) {
            intList.add(values[index]);
        }
        Collections.sort(intList);
        return intList.get(intList.size() - largeIndex);
    }
}

回答by Patison

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

回答by Nilesh Jadav

public class Test
{

public static int[] findTwoHighestDistinctValues(int[] array)
{
    int max = Integer.MIN_VALUE;
    int secondMax = Integer.MIN_VALUE;
    for (int value:array)
    {
        if (value > max)
        {
            secondMax = max;
            max = value;
        }
        else if (value > secondMax && value < max)
        {
            secondMax = value;
        }
    }
    return new int[] { max, secondMax };
}

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;
    int []ar = findTwoHighestDistinctValues(values);
    System.out.println("1 = "+ar[0]);
    System.out.println("2 = "+ar[1]);
}  
}

OUTPUT:

输出:

1 = 25

1 = 25

2 = 20

2 = 20

回答by Asharan

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.

@Nilesh Jadav 的回答涵盖了所有情况。在数组具有最大值是最后一个元素的情况下,@Peter Lawrey 的回答失败。例如,[10,2,5,1,8,20] 返回 20 和 8 以及接受的解决方案。

回答by user2517929

public static int Compute(int _arrValues[]){

        int _intX = _arrValues[0];
        int _intY = _arrValues[1];

        for(int i = 2; i < _arrValues.length; i++){

                if(_arrValues[i] > _intX){
                    _intX= values[i];
                }
                else if(_arrValues[i] > _intY){
                    _intY = values[i];   
                }
        }
        return _intX + _intY; 
    }