ここに質問を与えます。 https://www.careercup.com/question?id=9406769 which asks: 2つのソートされていないint配列がある場合、マージされソートされた配列のk番目の要素を探します。 1.2つのソートされていない配列からのMinHeapビルドでK要素を見つけるのが大きい(O)
から始まるインデックスで k個の要素は何以下溶液のビーゴ性能であろう(プリントは1):
object MergeTwoArraysFindK {
import scala.collection.mutable.PriorityQueue
def findK(arrayOne: Array[Int], arrayTwo: Array[Int], k: Int): Int = {
implicit val ord = Ordering[Int].reverse
val minHeap = new PriorityQueue[Int] ++= (arrayOne ++ arrayTwo).iterator
for (i <- 1 to k)
if (i == k)
return minHeap.dequeue()
else
minHeap.dequeue()
-1
}
def main(args: Array[String]): Unit = {
val arrayOne = Array[Int](3, 4, 9, 0, 1, 2, 4)
val arrayTwo = Array[Int](5, 4, 1, 0, 9, 8)
println(findK(arrayOne, arrayTwo, 4))
}
}
どこにいらっしゃいますか?あなたはあなたの業務の大切さを知っていますか? (キューに追加、dequueなど)? –
ところで、あなたは境界のある優先度のキューが必要かもしれません。 http://stackoverflow.com/questions/7878026/is-there-a-priorityqueue-implementation-with-fixed-capacity-and-custom-comparatoを参照してください。 –
私は答えがO(n)であるべきだと思います。ヒープ。今度は、おそらくn + O(log n)のヒープに2つの配列をマージすることによってヒープを構築することを含めなければならないと考えています。ここで、nは配列の連結であり、O(log n)は挿入です。私は正しい? – Fabio