What is the right approach when using STL container for median calculation?

后端 未结 10 949
再見小時候
再見小時候 2020-12-02 10:17

Let\'s say I need to retrieve the median from a sequence of 1000000 random numeric values.

If using anything but std::list, I have no (

10条回答
  •  长情又很酷
    2020-12-02 11:13

    you can use this approch. It also takes care of sliding window.
    Here days are no of trailing elements for which we want to find median and this makes sure the original container is not changed
    
    
    #include
    
    using namespace std;
    
    int findMedian(vector arr, vector brr, int d, int i)
    {
        int x,y;
        x= i-d;
        y=d;
        brr.assign(arr.begin()+x, arr.begin()+x+y);
    
    
        sort(brr.begin(), brr.end());
    
        if(d%2==0)
        {
            return((brr[d/2]+brr[d/2 -1]));
        }
    
        else
        {
            return (2*brr[d/2]);
        }
    
        // for (int i = 0; i < brr.size(); ++i)
        // {
        //     cout<>n>>days;
    
        vector arr;
        vector brr;
    
        for (int i = 0; i < n; ++i)
        {
            cin>>input;
            arr.push_back(input);
        }
    
        for (int i = days; i < n; ++i)
        {
            median=findMedian(arr,brr, days, i);
    
            
        }
    
    
    
        return 0;
    }
    

提交回复
热议问题