码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithm] How to use Max Heap to maintain K smallest items

时间:2019-03-05 23:06:18      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:int   ems   using   color   use   whether   struct   put   replace   

Let‘s say we are given an array:

[4,1,5,2,3,0,10]

We want to get K = 3 smallest items from the array and using Max heap data structure.

 

So this is how to think about it.

1. We take first K items put it into Max Heap:

     5

  /     \

4          1

 

2. Then we move forward to next element ‘2‘ in the array, we check

  • Whether 2 is smaller than current max item in heap, which is ‘5‘, if yes, then replace 5 with 2
  • Then re-arrange the heap

     4

   /    \        

 2         1

3. Repeat the process for items [3,0]

     3        2

   /    \                   /  \

 2         1              0    1

4. When the item is ‘10‘ which is larger than current max ‘2‘, we just ingore it.

5. In the end, we got K smallest items, we just need to print it out. (K smallest items are not ncessary in order)

[Algorithm] How to use Max Heap to maintain K smallest items

标签:int   ems   using   color   use   whether   struct   put   replace   

原文地址:https://www.cnblogs.com/Answer1215/p/10480327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!