dou7851 2015-03-26 10:04
浏览 44

如何剥离或切片SplHeap(也是SplMaxHeap,SplMinHeap)的底部项目?

I have a SplMaxHeap with 30 items. Now I want to strip the last 10 ones. How to do this in a decent and efficient way?

The only solutions I see so far is to copy the first 20 items to a new heap or to convert the heap to an array, use the array_slice and put them also in a new heap.

I even can't see a way to get something out of the heap not from the top.

I guess the reason for this is a limitation of the general design of a heap? I was also thinking to use a DoublyLinkedList, however there I am missing the automatic sorting.

  • 写回答

2条回答 默认 最新

  • duanmangxie7131 2015-04-11 13:19
    关注

    One approach is to create a new class derived from an SPL heap, which upon insert only keeps the top (or bottom, depending on the heap) n items.

    A super-basic example might look something like:

    class Top100 extends SplMinHeap
    {
        protected $limit = 100;
        public function insert($value)
        {
            parent::insert($value);
            while (count($this) > $this->limit) {
                $this->extract();
            }
        }
    }
    

    This is discussed further in Tobias Schlitt's 2010 article "Heap, heap, hooray!".

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度