forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
findMedianFromDataStream.swift
116 lines (94 loc) · 3.1 KB
/
findMedianFromDataStream.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
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?
*/
class MedianFinder {
let maxHeap = Heap(topToBottom: >) // left half
let minHeap = Heap(topToBottom: <) // right half
// make sure `maxHeap.count == minHeap.count || maxHeap.count == minHeap.count + 1`
func addNum(_ num: Int) {
if maxHeap.count == minHeap.count {
maxHeap.add(num)
minHeap.add(maxHeap.extract()!)
} else {
minHeap.add(num)
maxHeap.add(minHeap.extract()!)
}
}
func findMedian() -> Double {
var result = 0.0
var max: Double = 0.0
var min: Double = 0.0
if let m = maxHeap.peek() { max = Double(m) }
if let m = minHeap.peek() { min = Double(m) }
return maxHeap.count == minHeap.count ? Double((max + min) / 2.0) : min
}
}
// heap definition
class Heap {
private var heap = [Int]()
private let comparator: (_ top: Int, _ bottom: Int) -> Bool
init(topToBottom comparator: @escaping (Int, Int) -> Bool) {
self.comparator = comparator
}
var count: Int {
return heap.count
}
func add(_ num: Int) {
heap.append(num)
var curr = heap.count - 1
while curr > 0 {
let parent = (curr - 1) / 2
if !comparator(heap[parent], heap[curr]) {
heap.swapAt(curr, parent)
curr = parent
} else {
break
}
}
}
func extract() -> Int? {
guard heap.count > 0 else { return nil }
let result = heap[0]
let last = heap.removeLast()
if heap.count > 0 {
heap[0] = last
var curr = 0
while curr < heap.count {
let next: Int
let left = curr * 2 + 1, right = curr * 2 + 2
if right < heap.count {
next = comparator(heap[left], heap[right]) ? left : right
} else if left < heap.count {
next = left
} else {
break
}
if !comparator(heap[curr], heap[next]) {
heap.swapAt(curr, next)
curr = next
} else {
break
}
}
}
return result
}
func peek() -> Int? {
return heap.first
}
}