简体   繁体   中英

how to find second largest index of arraylist in java

I have to write a method that returns the second largest index of an ArrayList of integer values.

The array list is: 4 8 15 16 23 42 97 56 95 85 63 41 52 99 97 Q

The Q is there to mark the end of the input. I am using fileIn.hasNextInt() to read the input and check to see if it is an integer.

The problem I am having with my logic is it is only cycling through the ArrayList and returning the last index of the ArrayList and not the index of the second largest value.

Here is my code:

    public static int secondMaxIndex(ArrayList<Integer> intArray){
        int largest  = intArray.get(0);
        int largest2 = intArray.get(0);
        int maxIndex2 = 0;
        for( int i = 0; i <= intArray.size() - 1; i++){
            if( largest < intArray.get(i) ){
                largest = intArray.get(i);
            }
        }
        for( int j = 0; j <= intArray.size() - 1; j++){
            if( intArray.get(j) < largest ){
                maxIndex2 = j;
            }
        }
        return maxIndex2;
    }

You are inventing a wheel. ArrayList<Integer> intArray contains Integers by contract, no need to verify its elements. Just use natural sorting and pick second item from the end:

intArray.sort(Integer::compare);
return intArray.get(intArray.size - 2);
if ( intArray.get(j) < largest ) {
    maxIndex2 = j;
}

Here is your problem. Think about it, this code won't just return the second largest, it will return a number that is smaller than the largest number.

  public static int secondMaxIndex(ArrayList<Integer> intArray)
  {
    int largest  = intArray.get(0);
    Integer largest2 = null;
    int maxIndex = 0;
    int maxIndex2 = 0;

    for( int i = 0; i < intArray.size() ; i++)
    {
        if( largest < intArray.get(i) )
        {
            largest2 = largest;
            maxIndex2 = maxIndex;
            largest = intArray.get(i);
            maxIndex = i;
        }
        else if(largest2 == null || intArray.get(i) > largest2)
        {
             largest2 = intArray.get(i);
             maxIndex2 = i;
        }
    }

    return maxIndex2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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