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

FindMedianFromDataStream   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 15
eloc 32
c 1
b 0
f 0
dl 0
loc 58
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A findMedian2() 0 8 5
A __construct() 0 7 1
A addNum2() 0 6 2
A addNum() 0 10 2
A findMedian() 0 8 5
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