Skip to content

Commit 42ecf5c

Browse files
committed
get middle number
1 parent ab9f587 commit 42ecf5c

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package ch29_heap_solutions
2+
3+
import scala.collection.mutable
4+
5+
class MiddleNumberKeeper(val percent: Double) {
6+
7+
def this() = this(0.5)
8+
9+
val bigTop = new mutable.PriorityQueue[Int]()
10+
val smallTop = new mutable.PriorityQueue[Int]()(scala.math.Ordering.Int.reverse)
11+
12+
13+
def put(num: Int): Unit = {
14+
if (smallTop.nonEmpty && num >= smallTop.head) {
15+
smallTop += num
16+
adjustHeap()
17+
return
18+
}
19+
20+
//for any other scenario, we just put the item to bitTop then adjustHeap
21+
bigTop += num
22+
adjustHeap()
23+
}
24+
25+
def get(): Option[Int] = {
26+
bigTop.headOption
27+
}
28+
29+
private[this] def adjustHeap(): Unit = {
30+
val totalLength = smallTop.length + bigTop.length
31+
//deal with bigTop
32+
while (bigTop.length.doubleValue() / totalLength - percent > 0.0001) {
33+
//move item from bigTop to smallTop
34+
smallTop += bigTop.dequeue()
35+
}
36+
37+
//deal with smallTop
38+
while (smallTop.length.doubleValue() / totalLength - (1.0D - percent) > 0.0001) {
39+
bigTop += smallTop.dequeue()
40+
}
41+
}
42+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package ch29_heap_solutions
2+
3+
import org.scalatest.{FlatSpec, Matchers}
4+
5+
class MiddleNumberKeeperTest extends FlatSpec with Matchers {
6+
7+
behavior of "MiddleNumberKeeperTest"
8+
9+
it should "get middle of the array" in {
10+
val numKeeper = new MiddleNumberKeeper()
11+
for (i <- Range(0, 10)) {
12+
numKeeper.put(i)
13+
}
14+
15+
numKeeper.get().get should equal(4)
16+
}
17+
18+
it should "get 90% position of the array" in {
19+
val numKeeper = new MiddleNumberKeeper(0.9)
20+
for (i <- Range(0, 9)) {
21+
numKeeper.put(i)
22+
}
23+
numKeeper.put(9)
24+
25+
numKeeper.get().get should equal(8)
26+
}
27+
28+
}

0 commit comments

Comments
 (0)