[Swift]LeetCode295. 數據流的中位數 | Find Median from Data Stream

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-bjnqxznf-kv.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.git

For example,github

[2,3,4], the median is 3算法

[2,3], the median is (2 + 3) / 2 = 2.5api

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:app

  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?

中位數是有序列表中間的數。若是列表長度是偶數,中位數則是中間兩個數的平均值。優化

例如,spa

[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 }
相關文章
相關標籤/搜索