25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 20 | Hard<br />

20 9 Numbers are randomly generated and passed to a method Write a program to find<br />

and maintain <strong>the</strong> median value as new values are generated<br />

SOLUTIONS<br />

CareerCup com<br />

pg 91<br />

One solution is to use two priority heaps: a max heap for <strong>the</strong> values below <strong>the</strong> median, and<br />

a min heap for <strong>the</strong> values above <strong>the</strong> median The median will be largest value of <strong>the</strong> max<br />

heap When a new value arrives it is placed in <strong>the</strong> below heap if <strong>the</strong> value is less than or equal<br />

to <strong>the</strong> median, o<strong>the</strong>rwise it is placed into <strong>the</strong> above heap The heap sizes can be equal or<br />

<strong>the</strong> below heap has one extra This constraint can easily be restored by shifting an element<br />

from one heap to <strong>the</strong> o<strong>the</strong>r The median is available in constant time, so updates are O(lg n)<br />

1 private Comparator maxHeapComparator, minHeapComparator;<br />

2 private PriorityQueue maxHeap, minHeap;<br />

3 public void addNewNumber(int randomNumber) {<br />

4 if (maxHeap.size() == minHeap.size()) {<br />

5 if ((minHeap.peek() != null) &&<br />

6 randomNumber > minHeap.peek()) {<br />

7 maxHeap.offer(minHeap.poll());<br />

8 minHeap.offer(randomNumber);<br />

9 } else {<br />

10 maxHeap.offer(randomNumber);<br />

11 }<br />

12 }<br />

13 else {<br />

14 if(randomNumber < maxHeap.peek()){<br />

15 minHeap.offer(maxHeap.poll());<br />

16 maxHeap.offer(randomNumber);<br />

17 }<br />

18 else {<br />

19 minHeap.offer(randomNumber);<br />

20 }<br />

21 }<br />

22 }<br />

23 public static double getMedian() {<br />

24 if (maxHeap.isEmpty()) return minHeap.peek();<br />

25 else if (minHeap.isEmpty()) return maxHeap.peek();<br />

26 if (maxHeap.size() == minHeap.size()) {<br />

27 return (minHeap.peek() + maxHeap.peek()) / 2;<br />

28 } else if (maxHeap.size() > minHeap.size()) {<br />

29 return maxHeap.peek();<br />

30 } else {<br />

31 return minHeap.peek();<br />

32 }<br />

33 }<br />

2 9 0

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!