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 03:41

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 }; 
}
查看更多
太酷不给撩
3楼-- · 2020-02-06 03:42
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

查看更多
Viruses.
4楼-- · 2020-02-06 03:46

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.

查看更多
放我归山
5楼-- · 2020-02-06 03:50
 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);
}
查看更多
迷人小祖宗
6楼-- · 2020-02-06 03:51
   //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.

查看更多
爷、活的狠高调
7楼-- · 2020-02-06 03:54

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; 
}
查看更多
登录 后发表回答