find the kth largest element in a list and find the first k largest elements in a list

来源:互联网 发布:台湾中视源码 编辑:程序博客网 时间:2024/04/30 19:56

Problem 1: Given an unordered  list, find the kth largest element in this list.

Solution 1

  sort this list and you can immediately get the kth largest element.

  The time-complexity is O(NlogN).

 

Solution 2

   pythonic pseudocode:  

     find_kth(list, k):

        create a  container H with a fixed size k.

        Fullfill H with the first k elements in the specified list.

        for e in list[k: N -1]:

          min  = smallest(H)

          if e is larger than min:

             delete min from H

             add e into H

        return H[k - 1]

 

  Time-complexity: O(kN).

 

  A better choice of implemention of  the container in above code is Heap, which is easy to find the minimum element, delete it and add a new element.

 

 

Solution 3: quick select alogrithm

  Quick select alogrithm is very similar to quick sort.

  Pythonic pseudocode:

    quick_select(list, k):

        pivot = list[0].

        split list into two parts(smaller and larger), one contains elements equal to or smaller than pivot, the other one contains elements  larger than pivot.

        if len(larger) == k:

          return larger[k-1]

        elif len(larger) > k:

          return quick_select(larger, k)

        else:

          return quick_select(smaller, k - len(larger)

 

  Time Complexity: O(N)

 

  Implementions:

    erlang code:

      

 

   java code:

      

 

  

 

Problem 2: Given an unordered  list, find the first k largest elements in this list.

 

 

   This problem is similar to the first problem. Actually, if we  examine the three solutions of the first problem, we can see that we alread get the first k largest elements for finding the kth largest element . So we have solved this problem.