UglyNumberII   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 13
eloc 34
c 2
b 0
f 0
dl 0
loc 53
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B nthUglyNumber() 0 26 7
A nthUglyNumber2() 0 23 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class UglyNumberII
8
{
9
    public static function nthUglyNumber(int $n): int
10
    {
11
        if ($n <= 0) {
12
            return 0;
13
        }
14
        if ($n === 1) {
15
            return 1;
16
        }
17
        $ans = [1];
18
        $i2 = $i3 = $i5 = 0;
19
        while (count($ans) < $n) {
20
            [$m2, $m3, $m5] = [$ans[$i2] * 2, $ans[$i3] * 3, $ans[$i5] * 5];
21
            $min = min($m2, min($m3, $m5));
22
            if ($min === $m2) {
23
                $i2++;
24
            }
25
            if ($min === $m3) {
26
                $i3++;
27
            }
28
            if ($min === $m5) {
29
                $i5++;
30
            }
31
            $ans[] = $min;
32
        }
33
34
        return array_pop($ans);
35
    }
36
37
    public static function nthUglyNumber2(int $n): int
38
    {
39
        if ($n <= 0) {
40
            return 0;
41
        }
42
        if ($n === 1) {
43
            return 1;
44
        }
45
        $heap = new \SplMinHeap();
46
        $heap->insert(1);
47
        for ($i = 1; $i < $n; $i++) {
48
            $value = $heap->top();
49
            $heap->extract();
50
            while (!$heap->isEmpty() && $heap->top() === $value) {
51
                $value = $heap->top();
52
                $heap->extract();
53
            }
54
            $heap->insert($value * 2);
55
            $heap->insert($value * 3);
56
            $heap->insert($value * 5);
57
        }
58
59
        return $heap->top();
60
    }
61
}
62