27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

<strong>Solutions</strong> to Chapter 20 | Hard<br />

20.9 Numbers are r<strong>and</strong>omly generated <strong>and</strong> passed to a method. Write a program to find<br />

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

SOLUTIONS<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, <strong>and</strong><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 r<strong>and</strong>omNumber) {<br />

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

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

6 r<strong>and</strong>omNumber > minHeap.peek()) {<br />

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

8 minHeap.offer(r<strong>and</strong>omNumber);<br />

9 } else {<br />

10 maxHeap.offer(r<strong>and</strong>omNumber);<br />

11 }<br />

12 }<br />

13 else {<br />

14 if(r<strong>and</strong>omNumber < maxHeap.peek()){<br />

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

16 maxHeap.offer(r<strong>and</strong>omNumber);<br />

17 }<br />

18 else {<br />

19 minHeap.offer(r<strong>and</strong>omNumber);<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 />

CareerCup.com<br />

2 9 0

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

Saved successfully!

Ooh no, something went wrong!