-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFindMedianFromDataStream.php
67 lines (57 loc) · 1.75 KB
/
FindMedianFromDataStream.php
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
<?php
declare(strict_types=1);
namespace leetcode;
class FindMedianFromDataStream
{
private \SplMinHeap $small;
private \SplMaxHeap $large;
private bool $isEven = true;
private \SplMinHeap $min;
private \SplMinHeap $max;
public function __construct()
{
$this->small = new \SplMinHeap();
$this->large = new \SplMaxHeap();
$this->min = new \SplMinHeap();
$this->max = new \SplMinHeap();
}
public function addNum(int $num): void
{
if ($this->isEven) {
$this->large->insert($num);
$this->small->insert($this->large->extract());
} else {
$this->small->insert($num);
$this->large->insert($this->small->extract());
}
$this->isEven = !$this->isEven;
}
public function addNum2(int $num): void
{
$this->max->insert($num);
$this->min->insert(-$this->max->extract());
if ($this->min->count() > $this->max->count()) {
$this->max->insert(-$this->min->extract());
}
}
public function findMedian(): float
{
if ($this->isEven) {
return !$this->small->isEmpty() && !$this->large->isEmpty()
? ($this->small->top() + $this->large->top()) / 2.0
: 0;
} else {
return $this->small->isEmpty() ? 0 : $this->small->top();
}
}
public function findMedian2(): float
{
if ($this->min->count() < $this->max->count()) {
return $this->max->isEmpty() ? 0 : $this->max->top();
} else {
$max = $this->max->isEmpty() ? 0 : $this->max->top();
$min = $this->min->isEmpty() ? 0 : $this->min->top();
return ($max - $min) / 2.0;
}
}
}