295. Find Median from Data Stream
package LeetCode_295 import java.util.* /** * 295. Find Median from Data Stream * https://leetcode.com/problems/find-median-from-data-stream/description/ * * Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. For example, [2,3,4], the median is 3 [2,3], the median is (2 + 3) / 2 = 2.5 Design a data structure that supports the following two operations: void addNum(int num) - Add a integer number from the data stream to the data structure. double findMedian() - Return the median of all elements so far. Example: addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2 Follow up: If all integer numbers from the stream are between 0 and 100, how would you optimize it? If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it? * */
/* * solution: Tow PriorityQueue, minHeap and maxHeap, Time complexity: O(nlogn), Space complexity:O(1) * get element from PriorityQueu is O(1), * add new element in PriorityQueu is O(logn) * */ class MedianFinder() { /** initialize your data structure here. */ //change to max heap, because PriorityQueue in kotlin default is Min Heap val leftHeap = PriorityQueue<Int>{ a, b -> b - a } //min heap val rightHeap = PriorityQueue<Int>() fun addNum(num: Int) { if (leftHeap.isEmpty() || num < leftHeap.peek()) { leftHeap.offer(num) } else { rightHeap.offer(num) } //balance minHeap and maxHeap //the size of minHeap just can larger than the size fo maxHeap by 1 if (leftHeap.size < rightHeap.size) { leftHeap.offer(rightHeap.poll()) } else if (leftHeap.size - rightHeap.size == 2) { rightHeap.offer(leftHeap.poll()) } } fun findMedian(): Double { if (leftHeap.size>rightHeap.size){ return leftHeap.peek().toDouble() } else { val left = leftHeap.peek().toDouble() val right = rightHeap.peek().toDouble() return (left+right)/2 } } } /** * Your MedianFinder object will be instantiated and called as such: * var obj = MedianFinder() * obj.addNum(num) * var param_2 = obj.findMedian() */
标签:
PriorityQueue
, leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)