This is the 27th day of my participation in the August Genwen Challenge.More challenges in August

295. The median of data streams

The median is the number in the middle of an ordered list. If the list length is even, the median is the average of the middle two numbers.

For example,

The median of [2,3,4] is 3

The median of [2,3] is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

Void addNum(int num) – Adds an integer from the data stream to the data structure. Double findMedian() – Returns the current median for all elements. Example:

AddNum (1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2

How would you optimize your algorithm if all the integers in your data stream were in the range 0 to 100? How would you optimize your algorithm if 99% of the integers in your data stream were in the range 0 to 100?

#295. Find Median from Data Stream The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

For example, for arr = [2,3,4], the median is 3. For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5. Implement the MedianFinder class:

MedianFinder() initializes the MedianFinder object. void addNum(int num) adds the integer num from the data stream to the data structure. double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.  

Example 1:

Input [“MedianFinder”, “addNum”, “addNum”, “findMedian”, “addNum”, “findMedian”] [[], [1], [2], [], [3], [] Output [null, NULL, NULL, 1.5, null, 2.0]

Explanation MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addnum (3); // arr[1, 2, 3] medianFinder.findMedian(); / / return 2.0

Constraints:

-105 <= num <= 105 There will be at least one element in the data structure before calling findMedian. At most 5 * 104 calls will be made to addNum and findMedian.  

Follow up:

If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution? If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?

code

class MedianFinder { PriorityQueue<Integer> queMin; PriorityQueue<Integer> queMax; public MedianFinder() { queMin = new PriorityQueue<Integer>((a, b) -> (b - a)); queMax = new PriorityQueue<Integer>((a, b) -> (a - b)); } public void addNum(int num) { if (queMin.isEmpty() || num <= queMin.peek()) { queMin.offer(num); if (queMax.size() + 1 < queMin.size()) { queMax.offer(queMin.poll()); } } else { queMax.offer(num); if (queMax.size() > queMin.size()) { queMin.offer(queMax.poll()); } } } public double findMedian() { if (queMin.size() > queMax.size()) { return queMin.peek(); } return (quemin.peek () + quemax.peek ()) / 2.0; }}Copy the code