find median in a fixed-size moving window along a long sequence of data

前端 未结 5 1160
挽巷
挽巷 2021-02-04 09:41

Given a sequence of data (it may have duplicates), a fixed-sized moving window, move the window at each iteration from the start of the data sequence, such that (1) the oldes

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 10:14

    O(n*lg m) is easy:

    Just maintain your window as two std::sets, one for the lower half, one for the upper half. Insertion of a new element costs O(lg m), finding and removal of an old element costs the same. Determining the median using the method you described in your question costs O(1).

    As you slide the window over your sequence, in each iteration you remove the item falling out of the window (O(lg m)), insert the new item (O(lg m)) and compute the median (O(1)), resulting in a total of O(n lg m).

    This solution uses space O(m), of course but I don't think you can get away without storing the window's contents.

提交回复
热议问题