295. Find Median from Data Stream
For example: 1 2 -3 4 => the ans: -3 1 2 4 => Median is 1.5
separate into two heaps (minheap), large and small
ๆฆๅฟตๆฏๅๆๅ ฉ็พค, ๅฐ็็พคๅๆๅคง็, ๅคง็็พคๅๆๅฐ็,
็ตฑไธ้ฝ็จmin heap, ๆไปฅๅ ๅฐ small ๆ, ้ฝๆ็จ่ฒ ็ๅ ๅ ฅ,
้้-large.poll(), ๆๅฐ็ๅ ๅฐsmall
if (large.size() < small.size()) {
็จไพ็ถญๆๅ ฉ้ heap ๆธ้ๅนณ่กก,
็ถsmall ๅคชๅคๆ, ๅฉ็จlarge.add(-small.poll()); ๅ ๅๅปlarge
=> -small.poll() ๆญคๆ้็ถๆฏๅ
ถpoll min, ไฝๅ
ถๅฏฆๆๆฏๆ"ๆๅคง"็ๅ ๅ large (ๅ ็บไนๅ้ฝๆฏๆ่ฒ ้็ๅผๅ ๅฐsmall), ๅ ็บไนๅ่ฒ ้, ๆไปฅ่ฆๅจ่ฒ ๅไพ
็ถๅฅๆธๅๆธๆ, large ๆๆฏ่ผๅคๅๆธ,
ๅถๆธๅๆธๆ, large ๅsmallใ็ๅๆธๆไธๆจฃ
ๅฅๆธcase
For example: 1 2 -3
the ans: -3 1 2
when 1 enter, large.add(1)
small.add(-large.poll()) => small.add(-1)
=> small size > large size (ๅฅๆธๆ, ็ถญๆ large ๆฏ่ผๅคๅๆธ
=> -small.poll() -(-1) add to large
when 2 enter, large.add(2)
small.add(-large.poll()) => small.add(-1)
when -3 enter, large.add(-3)
small.add(-large.poll()) => small.add(3)
=> small size > large size
=> -small.poll() -(-1) add to large
ๅฅๆธๆ, ๅฐฑๅlarge ็ๆๅฐๅณๅฏ
ๅถๆธcase
For example: 1 2 -3 4
the ans: -3 1 2 4
small: 3, -1 => small ๅๆๅฐ (min heap peek()
large: 2, 4 => large ๅๆๅฐ (min heap peek()
ๅถๆธๆ, small large ๅ ฉ้ๆธ้็ธ็ญ,
ไธญไฝๆธ: large ๅๆๅฐ, small ๅๆๅฐ(ๅ ถๅฏฆไปฃ่กจๅฏฆ้ไธๆๅคง, ๅ ็บๅ ๅ ฅๆ้ฝไฝ้่ฒ ่),
็ธๅ ้ค2 โ 2 -(-1) /2 = 1.5 (ๅ ็บsmall ๆพๅ ฅๆ้ฝๆฏๆพ่ฒ ็, ๆไปฅ่ฆ็จ - ๅปๅ )
time: O(logn)
space: O(n)
Last updated