Return the two largest integers in an array of val

2020-02-06 03:31发布

问题:

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

}

回答1:

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


回答2:

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


回答3:

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

2 = 20



回答4:

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



回答5:

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


回答6:

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


回答7:

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.

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


回答8:

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


回答9:

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.



回答10:

 public static void main(String[] args) {

    int[] numbers = new int[]{1, 2, 5, 4, 57, 54, 656, 4};
    int temp = numbers[0];
    int max = temp;
    int lastMax = temp;

    for (int index = 1; index < numbers.length; index++){
        int currentIndex = numbers[index];

        // check any time is it bigger than current maximum value
        max = Math.max(max, currentIndex);

        // if is grow up then should be max != temp; set old Max in last or 
        // is not group up but current index is bigger then last index update last max value
        lastMax = max != temp ? temp : Math.max(currentIndex, lastMax);

        temp = max;
    }

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


回答11:

Try this out

int [] array1={10,2,5,1,8,20};

int largest= array1[0];

int seclargest=array1[0];

for (int i=1;i<array1.length;i++)
{
    if(largest <= array1[i])
    {
        seclargest=largest;
        largest=array1[i];  
    }   

}

System.out.println("largest and second largest are:" +largest + " " +seclargest);


回答12:

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

}


回答13:

   //Java8&9 makes this easier with a cleaner code
   int[] numbers = new int[]{1, 2, 5, 4, 57, 54, 656, 4};       
    int maxSize = 2;
    Arrays.stream(numbers) //stream
    .boxed()  //to Integer Object
    .sorted(Comparator.reverseOrder()) //sorted
    .limit(maxSize )  //keep N values
    .forEach(System.out::println); 

NB. We could use this astuce with any bean Object implementing comparable or by using a related custom comparator.



回答14:

public class TwoLargestIntArray {


    public static void main(String [] args){

        int a[]  = new int[5];

        a[0] = 110;
        a[1] = 50;
        a[2] = 15;
        a[3] = 30;
        a[4] = 60;

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

    }

    public static int twoLargest(int a[]){

        int firstMax = 0;
        int secondMax = 0;

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

                if(a[i]>firstMax) {
                    secondMax=firstMax;
                    firstMax = a[i];}
                    else if (a[i]>secondMax) {
                        secondMax= a[i];
                    }

                    }




        return  firstMax + secondMax; 
    }}


回答15:

If performance is not an issue here, which it shouldn't be on small arrays, this could be done with less code.

The most straightforward solution is to simply sort the array and return its last, and next to last value:

public static int[] twoLargest(int[] values) {
    Arrays.sort(values);
    return new int[]{values[values.length - 1], values[values.length - 2]};
}

The time complexity of the above code is O(n log (n)), as stated in the Javadoc for Arrays.sort():

Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

If expected input is an array with less than two elements, some error handling would need to be added, such as throwing an exception.



回答16:

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


标签: java arrays