Middle-Number in Data Flow topic description
How can I get the median in a data stream? If you read an odd number of values from the data stream, the median is the value in the middle after all the values have been sorted. If you read an even number of values from the data stream, the median is the average of the median two numbers after all the values are sorted.
Ideas
- We can use arrays, we need to sort them each time we take the median
- We can also use a balanced binary tree, but the process of constructing a tree is complex.
- We can also use size storage, but it's not easy.
- Finally, I chose to use the ArrayList stored in Java, sorted by the Collections.sort () method.
Code
Import java.util.ArrayList;Import java.util.Collections;public class Solution {arraylist<integer> numlist =Null Solution () {numlist =New arraylist<integer> ();}Publicvoid Insert (Integer num) {numlist.Add (num);} Public Double Getmedian () {collections. Sort (numlist); int length = numlist. size (); int temp = length/ 2; if (length% 2 = = 0) { return (double) (numlist. Get (temp) + numlist. Get (Temp- 1))/ 2;} else { return (double) (numlist. Get (temp)); } }}
Median in the data stream-the point of the sword