Test Failed
Push — master ( ff47b8...dce7a9 )
by Jinyun
02:58 queued 14s
created

FindMedianFromDataStream   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
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
    public function __construct()
14
    {
15
        $this->small = new \SplMinHeap();
16
        $this->large = new \SplMaxHeap();
17
    }
18
19
    public function addNum(int $num): void
20
    {
21
        if ($this->isEven) {
22
            $this->large->insert($num);
23
            $this->small->insert($this->large->extract());
24
        } else {
25
            $this->small->insert($num);
26
            $this->large->insert($this->small->extract());
27
        }
28
        $this->isEven = !$this->isEven;
29
    }
30
31
    public function findMedian(): float
32
    {
33
        if ($this->isEven) {
34
            return !$this->small->isEmpty() && !$this->large->isEmpty()
35
                ? ($this->small->top() + $this->large->top()) / 2.0
36
                : 0;
37
        } else {
38
            return $this->small->isEmpty() ? 0 : $this->small->top();
39
        }
40
    }
41
}
42