简体   繁体   English

如何在Java中找到arraylist的第二大索引

[英]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. 我必须编写一个返回整数值ArrayList的第二大索引的方法。

The array list is: 4 8 15 16 23 42 97 56 95 85 63 41 52 99 97 Q 数组列表为: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. Q在那里标记输入的结束。 I am using fileIn.hasNextInt() to read the input and check to see if it is an integer. 我正在使用fileIn.hasNextInt()读取输入并检查是否为整数。

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. 我的逻辑存在的问题是,它仅循环遍历ArrayList并返回ArrayList的最后一个索引,而不是第二大值的索引。

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. ArrayList<Integer> intArray通过合同包含Integers ,无需验证其元素。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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