You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: leetcode/hard/295_find_median_from_data_stream.md
+3-2Lines changed: 3 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,14 +1,15 @@
1
1
# 295. Find Median from Data Stream
2
2
3
3
## Sort solution
4
-
- Runtime: O(log(N)) for addNum() and O(1) for findMedian(), in total O(Nlog(N))
4
+
- Runtime: O(N) for addNum() and O(1) for findMedian(), in total O(N\*N) worst case)
5
5
- Space: O(N)
6
6
- N = Number of elements in array
7
7
8
8
This solution is fairly simple, as long as we keep a sorted order of numbers, we can figure out the median quickly.
9
9
10
10
However, it is important to note that if we instead did a different approach where we would add the value into the list then sort it only when findMedian() was called, it would actually cause a slower run-time, O(N * Nlog(N)).
11
11
The worst case is when we call findMedian() after each newly inserted number.
12
+
We would basically be sorting the entire array N times.
12
13
That is because every time we would sort, the list keeps growing, we aren't utilizing the fact that the list is already sorted.
13
14
With an already sorted list, we can just perform a binary search and insert the new number instead of resorting an already sorted list for each number.
14
15
@@ -35,7 +36,7 @@ class MedianFinder:
35
36
```
36
37
37
38
## Two Heap Solution
38
-
- Runtime: O(log(N)) for addNum() and O(1) for findMedian(),in total O(Nlog(N))
39
+
- Runtime: O(log(N)) for addNum() and O(1) for findMedian(),in total O(Nlog(N)) worst case
0 commit comments