295.Find-Median-from-Data-Stream
295. Find Median from Data Stream
题目地址
https://leetcode.com/problems/find-median-from-data-stream/
https://www.lintcode.com/problem/find-median-from-data-stream
题目描述
代码
Approach 1: Simple Sorting
Time complexity: O(nlogn)
+ O(1)
≃ O(nlogn)
Adding a number takes amortized O(1) time for a container with an efficient resizing scheme.
Finding the median is primarily dependent on the sorting that takes place. This takes
O(nlogn)
time for a standard comparative sort.
Approach #2 Two heap
Max-heap
small
has the smaller half of the numbers.Min-heap
large
has the larger half of the numbers.
Complexity Analysis
Time complexity:
O(5⋅logn) + O(1) ≈ O(logn)
At worst, there are three heap insertions and two heap deletions from the top. Each of these takes about
O(logn)
time.Finding the mean takes constant
O(1)
time since the tops of heaps are directly accessible.
Space complexity:
O(n)
linear space to hold input in containers.
Last updated