[Swift]LeetCode295. 数据流的中位数 | Find Median from Data Stream
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10241288.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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?
中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
例如,
[2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
- void addNum(int num) - 从数据流中添加一个整数到数据结构中。
- double findMedian() - 返回目前所有元素的中位数。
示例:
addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2
进阶:
- 如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
- 如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?
736ms
1 class MedianFinder { 2 var nums : [Int] 3 4 /** initialize your data structure here. */ 5 init() { 6 nums = [Int]() 7 } 8 9 func addNum(_ num: Int) { 10 if nums.isEmpty { 11 nums.append(num) 12 return 13 } 14 15 var left = 0 16 var right = nums.count - 1 17 while left <= right { 18 let mid = (left + right) / 2 19 if nums[mid] < num { 20 left = mid + 1 21 }else if nums[mid] == num { 22 left = mid 23 break 24 }else { 25 right = mid - 1 26 } 27 } 28 29 nums.insert(num, at: left) 30 } 31 32 func findMedian() -> Double { 33 if nums.isEmpty { 34 return 0 35 } 36 37 if nums.count % 2 == 1 { 38 return Double(nums[nums.count / 2]) 39 }else { 40 let r1 = nums[nums.count / 2] 41 let r2 = nums[nums.count / 2 - 1] 42 return Double(r1 + r2) / 2 43 } 44 } 45 } 46 47 /** 48 * Your MedianFinder object will be instantiated and called as such: 49 * let obj = MedianFinder() 50 * obj.addNum(num) 51 * let ret_2: Double = obj.findMedian() 52 */
1208ms
1 class MedianFinder { 2 //Holds the small part of the stream but track the largest one 3 let maxQueue: PriorityQueue<Int> 4 //Holds the larger part of the stream but track the smallest one 5 let minQueue: PriorityQueue<Int> 6 /** initialize your data structure here. */ 7 init() { 8 maxQueue = PriorityQueue<Int>(priorityFunction:{ $0 > $1 }) 9 minQueue = PriorityQueue<Int>(priorityFunction:{ $0 < $1 }) 10 } 11 12 func addNum(_ num: Int) { 13 maxQueue.enqueue(num) 14 if let num = maxQueue.dequeue() { 15 minQueue.enqueue(num) 16 if maxQueue.count < minQueue.count { 17 if let minNum = minQueue.dequeue() { 18 maxQueue.enqueue(minNum) 19 } 20 } 21 } 22 } 23 24 func findMedian() -> Double { 25 if maxQueue.count == minQueue.count { 26 return (Double(maxQueue.peek()!) + Double(minQueue.peek()!)) / 2 27 } else { 28 return Double(maxQueue.peek()!) 29 } 30 } 31 } 32 33 /** 34 * Your MedianFinder object will be instantiated and called as such: 35 * let obj = MedianFinder() 36 * obj.addNum(num) 37 * let ret_2: Double = obj.findMedian() 38 */ 39 40 41 public class PriorityQueue<Element> { 42 var elements: [Element] 43 var priorityFunction: (Element, Element) -> Bool 44 var count: Int { return elements.count } 45 46 init(priorityFunction:@escaping (Element, Element) -> Bool) { 47 self.elements = [Element]() 48 self.priorityFunction = priorityFunction 49 } 50 51 func isHigherPriority(at index:Int,than secondIndex:Int) -> Bool { 52 return self.priorityFunction(elements[index], elements[secondIndex]) 53 } 54 55 func enqueue(_ element:Element) { 56 elements.append(element) 57 siftUp(index: elements.count - 1) 58 } 59 60 func dequeue() -> Element? { 61 if elements.count == 0 { 62 return nil 63 } 64 65 elements.swapAt(0, elements.count - 1) 66 let element = elements.removeLast() 67 siftDown(index: 0) 68 return element 69 } 70 71 func peek() -> Element? { 72 return elements.first 73 } 74 75 func siftUp(index:Int) { 76 if index == 0 { 77 return 78 } 79 80 let parent = parentIndex(for: index) 81 if isHigherPriority(at: index, than: parent) { 82 elements.swapAt(index, parent) 83 siftUp(index: parent) 84 } 85 } 86 87 func siftDown(index:Int) { 88 var highIndex = index 89 let leftIndex = leftChildIndex(for: index) 90 let rightIndex = rightChildIndex(for: index) 91 if leftIndex < count && isHigherPriority(at: leftIndex, than: index) { 92 highIndex = leftIndex 93 } 94 if rightIndex < count && isHigherPriority(at: rightIndex, than: highIndex) { 95 highIndex = rightIndex 96 } 97 if highIndex == index { 98 return 99 } else { 100 elements.swapAt(highIndex, index) 101 siftDown(index: highIndex) 102 } 103 } 104 105 func parentIndex(for index:Int) -> Int { 106 return (index - 1)/2 107 } 108 109 func leftChildIndex(for index:Int) -> Int { 110 return index * 2 + 1 111 } 112 113 func rightChildIndex(for index:Int) -> Int { 114 return index * 2 + 2 115 } 116 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了