• Find Median from Data Stream

Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
* void addNum(int num) - Add a integer number from the data stream to the data structure.
* double findMedian() - Return the median of all elements so far.

For example:
1. add(1)
2. add(2)
3. findMedian() -> 1.5
4. add(3)
5. findMedian() -> 2

Solution:
1. class MedianFinder {
2. // Max heap
3. PriorityQueue left = new PriorityQueue<>(new Comparator() {
4. public int compare(Integer a, Integer b) { return b - a; }
5. });
6. 7. // Min heap
8. PriorityQueue right = new PriorityQueue<>(new Comparator() {
9. public int compare(Integer a, Integer b) { return a - b; }
10. });
11. 12. // Adds a number into the data structure.
13. public void addNum(int num) {
14. double m = findMedian();
15. 16. int diff = left.size() - right.size();
17. 18. // left and right are balanced
19. if (diff == 0) {
20. if (num < m) {
21. left.offer(num);
22. } else {
23. right.offer(num);
24. }
25. }
26. // left has more elements than right
27. else if (diff > 0) {
28. if (num < m) {
29. if (left.size() > 0) right.offer(left.poll());
30. left.offer(num);
31. } else {
32. right.offer(num);
33. }
34. }
35. // right has more elements than left
36. else {
37. if (num < m) {
38. left.offer(num);
39. } else {
40. if (right.size() > 0) left.offer(right.poll());
41. right.offer(num);
42. }
43. }
44. }
45. 46. // Returns the median of current data stream
47. public double findMedian() {
48. if (left.size() == 0 && right.size() == 0) {
49. return 0.0;
50. }
51. 52. int diff = left.size() - right.size();
53. 54. // left and right are balanced
55. if (diff == 0) {
56. return (left.peek() + right.peek()) / 2.0;
57. }
58. // left has more elements than right
59. else if (diff > 0) {
60. return left.peek();
61. }
62. // right has more elements than left
63. else {
64. return right.peek();
65. }
66. }
67. };
68. 69. // Your MedianFinder object will be instantiated and called as such:
70. // MedianFinder mf = new MedianFinder();
71. // mf.addNum(1);
72. // mf.findMedian();