Sword refers to Offer-60-the median in the data stream

Title description

How to get the median in a data stream? If an odd number of values ​​are read from the data stream, the median is the value in the middle after all the values ​​are sorted. If you read an even number of values ​​from the data stream, then the median is the average of the middle two numbers after all the numbers are sorted. We use the Insert() method to read the data stream, and use the GetMedian() method to get the median of the currently read data.

Problem solving ideas

In fact, solving this problem is not troublesome. But optimization is troublesome. I thought of a solution. Optimization can only depend on the boss

Code

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
    
    
 
    ArrayList<Integer> list = new ArrayList<Integer>();
    public void Insert(Integer num) {
    
    
        list.add(num);
    }

    public Double GetMedian() {
    
    
        Collections.sort(list);
        int size = list.size();
        if(size%2==0){
    
    
            //如果是偶数个
            return new Double(list.get(size/2-1)+list.get(size/2))/2;
        }else{
    
    
            return new Double(list.get((size+1)/2 - 1));
        }
    }


}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107594216