Median in the data stream-the point of the sword

Source: Internet
Author: User

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
    1. We can use arrays, we need to sort them each time we take the median
    2. We can also use a balanced binary tree, but the process of constructing a tree is complex.
    3. We can also use size storage, but it's not easy.
    4. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.