简体   繁体   English

找到第二个和第三个最大元素数组java

[英]find second and third maximum element array java

I have to find 1st, 2nd, and 3rd largest array.我必须找到第一、第二和第三大数组。 I know I could simply sort it and return array[0], array[1], array[3].我知道我可以简单地对其进行排序并返回数组[0]、数组[1]、数组[3]。 But the problem is, i need the index, not the value.但问题是,我需要索引,而不是值。 For example if i have float[] listx={8.0, 3.0, 4.0, 5.0, 9.0} it should return 4, 0, and 3.例如,如果我有float[] listx={8.0, 3.0, 4.0, 5.0, 9.0}它应该返回float[] listx={8.0, 3.0, 4.0, 5.0, 9.0}和 3。

Here's the code I have but it doesn't work:这是我的代码,但它不起作用:

//declaration max1-3        
public void maxar (float[] listx){

    float maxel1=0;
    float maxel2=0;
    float maxel3=0;

    for (int i=0; i<listx.length; i++){
        if(maxel1<listx[i])
        {maxel1=listx[i];
        max1=i;
        }
    }
    listx[max1]=0; //to exclude this one in nextsearch

    for (int j=0; j<listx.length; j++){
        if(listx[j]>maxel2)
        {maxel2=listx[j];
        max2=j;
        }
    }
    listx[max2]=0;

    for (int k=0; k<listx.length; k++){
        if(listx[k]>maxel3)
        {maxel3=listx[k];
        max3=k;
        }
    }
}

I get max1 right but after that all the elements turns to 0. hence max2 and max3 become 0. Please suggest me what is wrong with this solution.我得到 max1 正确,但之后所有元素都变为 0。因此 max2 和 max3 变为 0。请告诉我这个解决方案有什么问题。 Thank you.谢谢你。

You can find the three elements using a single loop, and you don't need to modify the array. 您可以使用单个循环找到这三个元素,而无需修改数组。

When you come across a new largest element, you need to shift the previous largest and the previous second-largest down by one position. 当您遇到一个新的最大元素时,您需要将之前的最大值和前一个第二大值向下移动一个位置。

Similarly, when you find a new second-largest element, you need to shift maxel2 into maxel3 . 同样,当您找到新的第二大元素时,您需要将maxel2转换为maxel3

Instead of using the three variables, you might want to employ an array. 您可能希望使用数组,而不是使用这三个变量。 This will enable you to streamline the logic, and make it easy to generalize to k largest elements. 这将使您能够简化逻辑,并使其易于推广到k最大元素。

在阵列上进行3次传递:在第一次传递查找值和最大元素M1第一个索引,第二次传递查找值和最小元素M2第一个索引(小于M1和第三次传递查找值/第一个索引M3 < M2

Try this code it will work :) 尝试这个代码它会工作:)

  public class Array
    {
  public void getMax( double ar[] )
   {
    double max1 = ar[0]; // Assume the first
    double max2 = ar[0]; // element in the array
    double max3 = ar[0]; // is the maximum element.
    int ZERO = 0; 
     // Variable to store inside it the index of the max value to set it to zero.

    for( int i = 0; i < ar.length; i++ )
    {
        if( ar[i] >= max1)
        {
            max1 = ar[i];
            ZERO = i;
        }
    }

    ar[ZERO] = 0; // Set the index contains the 1st max to ZERO.

    for( int j = 0; j < ar.length; j++ )
    {
        if( ar[j] >= max2 )
        {
            max2 = ar[j];
            ZERO = j;
        }
    }

    ar[ZERO] = 0; // Set the index contains the 2st max to ZERO.

    for( int k = 0; k < ar.length; k++ )
    {
        if( ar[k] >= max3 )
        {
            max3 = ar[k];
            ZERO = k;
        }
    }

            System.out.println("1st max:" + max1 + ", 2nd: " +max2 + ",3rd: "+ max3);                              
   }

public static void main(String[] args)
{
    // Creating an object from the class Array to be able to use its methods.
    Array array = new Array();
    // Creating an array of type double.
    double a[] = {2.2, 3.4, 5.5, 5.5, 6.6, 5.6};

    array.getMax( a ); // Calling the method that'll find the 1st max, 2nd max, and      and 3rd max.
}

  }

I suggest making a single pass instead of three for optimization. 我建议一次通过而不是三次通过优化。 The code below works for me. 下面的代码适合我。 Note that the code does not assert that listx has at least 3 elements. 请注意,代码listx至少包含3个元素。 It is up to you to decide what should happen in case it contains only 2 elements or less. 如果它只包含2个或更少的元素,由您来决定应该发生什么。

What I like about this code is that it only does one pass over the array, which in its best case would have faster running time compared to doing three passes, with a factor proportionate to the number of elements in listx . 我喜欢这个代码的是它只对数组进行一次传递,在最好的情况下,与三次传递相比,运行时间更快,其中一个因子与listx的元素数量成比例。

Assume i1 , i2 and i3 store the indices of the three greatest elements in listx , and i0 is one of i1, i2 and i3 that points to the smallest element. 假设i1i2i3存储listx三个最大元素的listx ,而i0是指向最小元素的i1,i2i3之一。 In the beginning, i1 = i2 = i3 because we haven't found the largest elements yet. 在开始时, i1 = i2 = i3,因为我们还没有找到最大的元素。 So let i0 = i1 . 所以让i0 = i1 If we find a new index j such that that listx[j] > listx[i0] , we set i0 = j , replacing that old index with an index that leads to a greater element. 如果我们找到一个新的索引j ,使得listx[j] > listx[i0] ,我们设置i0 = j ,用一个导致更大元素的索引替换旧索引。 Then we find the index among i1, i2 and i3 that now leads to the smallest element of out the three, so that we can safely discard that one in case a new large element comes along. 然后我们找到i1,i2i3中的索引它们现在导致三个中的最小元素,这样我们就可以安全地丢弃那个以防新的大元素出现。

Note : This code is in C, so translate it to Java if you want to use it. 注意 :此代码在C中,因此如果要使用它,请将其转换为Java。 I made sure to use similar syntax to make that easier. 我确保使用类似的语法来使这更容易。 (I wrote it in C because I lacked a Java testing environment.) (我在C中写道,因为我缺少Java测试环境。)

void maxar(float listx[], int count) {
    int maxidx[3] = {0};

    /* The index of the 3rd greatest element
     * in listx.
     */
    int max_3rd = 0;

    for (int i = 0; i < count; i++) {
        if (listx[maxidx[max_3rd]] < listx[i]) {
            /* Exchange 3rd greatest element
             * with new greater element.
             */
            maxidx[max_3rd] = i;

            /* Find index of smallest maximum. */
            for (int j = (max_3rd + 1) % 3; j != max_3rd; j = (j + 1) % 3) {
                if (listx[maxidx[j]] < listx[maxidx[max_3rd]]) {
                    max_3rd = j;
                }
            }
        }
    }

    /* `maxidx' now contains the indices of
     * the 3 greatest values in `listx'.
     */

    printf("3 maximum elements (unordered):\n");
    for (int i = 0; i < 3; i++) {
        printf("index: %2d, element: %f\n", maxidx[i], listx[maxidx[i]]);
    }
}
public class ArrayExample {
    public static void main(String[] args) {
        int secondlargest = 0;
        int thirdLargest=0;
        int largest = 0;
        int arr[] = {5,4,3,8,12,95,14,376,37,2,73};
        for (int i = 0; i < arr.length; i++) {
            if (largest < arr[i]) {
                secondlargest = largest;
                largest = arr[i];
            }
            if (secondlargest < arr[i] && largest != arr[i])
                secondlargest = arr[i];
            if(thirdLargest<arr[i] && secondlargest!=arr[i] && largest!=arr[i] && thirdLargest<largest && thirdLargest<secondlargest)
                thirdLargest =arr[i];
        }
        System.out.println("Largest number is: " + largest);
        System.out.println("Second Largest number is: " + secondlargest);
        System.out.println("third Largest number is: " + thirdLargest);
    }
}
def third_mar_array(arr):
    max1=0
    max2=0
    max3=0
    for i in range(0,len(arr)-1):
         if max1<arr[i]:
             max1=arr[i]
             max_in1=i
    arr[max_in1]=0
    for j in range(0,len(arr)-1):
         if max2<arr[j]:
             max2=arr[j]
             max_in2=j
    arr[max_in2]=0
    for k in range(0,len(arr)-1):
         if max3<arr[k]:
             max3=arr[k]
             max_in3=k
    #arr[max_in3]=0
    return max3

n=[5,6,7,3,2,1]

f=first_array(n)
print f
import java.util.Scanner;

class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int testcase = sc.nextInt();

        while (testcase-- > 0) {
            int sizeOfArray = sc.nextInt();
            int[] arr = new int[sizeOfArray];
            for (int i = 0; i < sizeOfArray; i++) {
                arr[i] = sc.nextInt();
            }

            int max1, max2, max3;
            max1 = 0;
            max2 = 0;
            max3 = 0;

            for (int i = 0; i < sizeOfArray; i++) {
                if (arr[i] > max1) {
                    max3 = max2;
                    max2 = max1;
                    max1 = arr[i];
                }
                else if (arr[i] > max2) {
                    max3 = max2;
                    max2 = arr[i];
                }
                else if (arr[i] > max3) {
                    max3 = arr[i];
                }
            }

            System.out.println(max1 + " " + max2 + " " + max3);
        }
    }
}

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

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