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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值