The three greatest values ​​in an array

To find the three largest elements in an array (length 100), is a combination of the for and if loop (s) the most efficient way, or is there a more efficient method?

+3
source share
10 answers

Your question is not very clear to me.

The most efficient way would be to maintain the maximum size heap 3and insert the elements of the array into the maximum heap one at a time.

In the end, the elements 3in your maximum heap are the largest elements 3in the original array.

max M N , M.

+7

100 -3 , - .

, if, 3 , .

N M-, , .

+4

, , , . - :

int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE;  //assuming integer elements in the array

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

N , , , .

+4

java, SortedSet (, TreeSet), , (log (n)), , descendingIterator(), .

+2

, 3, :

int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE; // assuming integer elements in the array

for (int i = 0; i < theArray.length; i++) {
    if (theArray[i] > max1) {
        max3 = max2;
        max2 = max1;
        max1 = theArray[i];
    } else if (theArray[i] > max2) {
        if (max1 == theArray[i]) {
            // Neglect as already present in max1
        } else {
            max3 = max2;
            max2 = theArray[i];
        }
    } else if (theArray[i] > max3) {
        if (max1 == theArray[i] || max2 == theArray[i]) {
            // Neglect as already present in max1 OR max2
        } else {
            max3 = theArray[i];
        }
    }
}                   
+1

, , for ( - .)

, .

0

, , ( ).

0

( ) ( Merge Sort), 3 .

0

Several people post that sorting is the way to go and then grab the top 3. However, if there is an O (log N) insert in the sorted collection, you will need to do it N times or do O (NlogN) (which, by the way, this is the worst case scenario (N ^ 2), you get NlogN efficiency as opposed to just O (N) iterating over an array with max1 / max2 / max3, like Riley above, Sorting or pasting into a sorted collection is the easiest, but not the most effective.

0
source
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a[10] = {-10,50,200,30,45,70,780,850,10,900};
    int i=0;
    int Max[3]={0};
    for(i=0;i<10;i++){
        if(Max[2]<a[i])
            Max[2] = a[i];
    }
    for(i=0;i<10;i++){
        if(Max[1]<a[i] && a[i]<Max[2])
            Max[1] = a[i];
    }
    for(i=0;i<10;i++){
        if(Max[0]<a[i] && a[i]<Max[1])
            Max[0] = a[i];
    }
    printf("%d %d %d",Max[2],Max[1],Max[0]);
    return 0;
}
0
source

Source: https://habr.com/ru/post/1768455/


All Articles