【问题标题】:Distinct elements in priority queue优先级队列中的不同元素
【发布时间】:2019-03-10 07:46:44
【问题描述】:

我正在使用这个有界优先级队列的实现,https://gist.github.com/ryanlecompte/5746241,它运行良好。但是,我希望这个队列不包含任何具有相同排序“ord”的元素。我怎样才能做到这一点?

我尝试通过提供函数 lteq 而不是 lt 来更新 MaybeReplaceLowest 函数。

private def maybeReplaceLowest(a: A) {
    if (ord.lteq(a, head)) {
      dequeue()
      super.+=(a)
    }
  }

但我认为它不起作用,因为与新元素具有相同顺序的元素可能不在头部。有什么办法可以快速解决这个问题?

非常感谢。

【问题讨论】:

    标签: scala priority-queue


    【解决方案1】:

    Scala PriorityQueue 是使用 Array 实现的。这对于查找操作非常低效,您需要为每个插入执行此操作(检查该元素是否已存在于队列中。

    对于TreeSet 是查找和有序存储的理想选择。 但由于这是一个密封类(scala-2.12.8),我创建了复合类

    import scala.collection.mutable
    
    class PrioritySet[A](val maxSize:Int)(implicit ordering:Ordering[A]) {
        var set = mutable.TreeSet[A]()(ordering)
    
        private def removeAdditional(): this.type = {
            val additionalElements = set.size - maxSize
            if( additionalElements > 0) { set = set.drop(additionalElements) }
            this
        }
    
        def +(elem: A): this.type = {
            set += elem
            removeAdditional()
        }
    
        def ++=(elem: A, elements: A*) : this.type = {
            set += elem ++= elements 
            removeAdditional()
        }
    
        override def toString = this.getClass.getName + set.mkString("(", ", ", ")")
    }
    

    这可以用作

    >>> val set = new PrioritySet[Int](4)
    >>> set ++=(1000,3,42,2,5, 1,2,4, 100)
    >>> println(set)
    PrioritySet(5, 42, 100, 1000)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 2013-02-13
      相关资源
      最近更新 更多