Finding the first n largest elements in an array

后端 未结 8 437
不思量自难忘°
不思量自难忘° 2020-12-09 04:42

I have got an array containing unique elements. I need to find out the first n largest elements in the array in the least complexity possible. The solution that I could thin

相关标签:
8条回答
  • 2020-12-09 05:17

    Find the kth biggest element, using selection algorithm.
    Next, iterate the array and find all elements which are larger/equal it.

    complexity: O(n) for selection and O(n) for iterating, so the total is also O(n)

    0 讨论(0)
  • 2020-12-09 05:20

    Use a modified version of Quick Sort. You do not need to actually sort the whole array. You only need to partition N elements larger than the pivot value. For more information, please read Introduction to Algorithms.

    0 讨论(0)
  • 2020-12-09 05:20

    You can use a Priority Queue using Heap (maxHeap) to solve this. Perform heap n times to get the first n largest elements. Each Heap operation takes O(log N) time, so N heap operations would result in O(N log N) time.

    0 讨论(0)
  • 2020-12-09 05:23

    You can do this in O(n) if your elements are integers (or any integral type) within a range, i to k inclusive with k >= i. With this constraint, you can apply "bucket sort" to this.

    The idea is quite simple. Allocate k - i + 1 buckets. Now, iterate through your collection and increment the bucket for that integer. Then, at the end, you can "recreate" the sorted list by creating as many integers that were found (i.e. the bucket number).

    For example,

    int collection[] = { 10, 4, 7, 1, 9, 0, 12 }; // maximum value to expect is 12, minimum is 0
    int buckets[ 13 ] = { 0 };
    
    for( int i = 0; i < 13; i++ )
    {
          int n = collection[ i ];
          buckets[ n ]++;
    }
    
    
    // the first n largest elements (n = 4)
    
    for( int j = 12; j >= 12 - 4; j-- )
    {
          int n = buckets[ j ];
    
          while( n > 0 )
          {
               printf( "%d ", j );
               n--;
          }
    }
    printf( "\n" ); 
    
    0 讨论(0)
  • 2020-12-09 05:25

    I tried this as per @Alexandre C.

    This gets the top 10 items of a unbounded input. It breaks after it processed 20 items from the input.

    import random
    import time
    top_10_items = []
    cnt = 1
    while True:
        rand = random.randint(1,100)
        print(rand)
    
        time.sleep(1)
        if len(top_10_items) !=10:
            top_10_items.append(rand)
        else:
            m = min(top_10_items)
            if rand > m:
                top_10_items.append(rand)
                top_10_items.remove(m)
    
        print(top_10_items)
    
        cnt+=1
        if cnt==20:
            break
    
    0 讨论(0)
  • 2020-12-09 05:31

    The usual trick to select the n largest elements is to maintain a min-priority queue.

    • Unconditionnally insert into the queue the n first elements
    • For each remaining element x, insert x if it is greater than the least element of the queue (O(log n) operation), and remove the least element (O(log n)).
    • When done, the priority queue contains n elements, which are the n largest elements of the original array.

    Total complexity: O(N log n) where N is the total number of elements in the array.

    I leave to you as an exercise the implementation details (first step is to learn about priority queues, and implement one).

    0 讨论(0)
提交回复
热议问题