• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Swift]LeetCode295.数据流的中位数|FindMedianfromDataStream

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10241288.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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:

  1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  2. 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

进阶:

  1. 如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
  2. 如果数据流中 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 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap