Test Failed
Push — master ( dce7a9...89f7de )
by Jinyun
02:42
created

FindMedianFromDataStream::addNum2()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class FindMedianFromDataStream
8
{
9
    private \SplMinHeap $small;
10
    private \SplMaxHeap $large;
11
    private bool $isEven = true;
12
13
    private \SplMinHeap $min;
14
    private \SplMinHeap $max;
15
16
    public function __construct()
17
    {
18
        $this->small = new \SplMinHeap();
19
        $this->large = new \SplMaxHeap();
20
21
        $this->min = new \SplMinHeap();
22
        $this->max = new \SplMinHeap();
23
    }
24
25
    public function addNum(int $num): void
26
    {
27
        if ($this->isEven) {
28
            $this->large->insert($num);
29
            $this->small->insert($this->large->extract());
30
        } else {
31
            $this->small->insert($num);
32
            $this->large->insert($this->small->extract());
33
        }
34
        $this->isEven = !$this->isEven;
35
    }
36
37
    public function addNum2(int $num): void
38
    {
39
        $this->max->insert($num);
40
        $this->min->insert(-$this->max->extract());
41
        if ($this->min->count() > $this->max->count()) {
42
            $this->max->insert(-$this->min->extract());
43
        }
44
    }
45
46
    public function findMedian(): float
47
    {
48
        if ($this->isEven) {
49
            return !$this->small->isEmpty() && !$this->large->isEmpty()
50
                ? ($this->small->top() + $this->large->top()) / 2.0
51
                : 0;
52
        } else {
53
            return $this->small->isEmpty() ? 0 : $this->small->top();
54
        }
55
    }
56
57
    public function findMedian2(): float
58
    {
59
        if ($this->min->count() < $this->max->count()) {
60
            return $this->max->isEmpty() ? 0 : $this->max->top();
61
        } else {
62
            $max = $this->max->isEmpty() ? 0 : $this->max->top();
63
            $min = $this->min->isEmpty() ? 0 : $this->min->top();
64
            return ($max - $min) / 2.0;
65
        }
66
    }
67
}
68