Test Failed
Push — master ( 01c2bc...8ddc48 )
by Jinyun
03:08
created

ProductOfArrayExceptSelf::productExceptSelf2()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 17
rs 9.9
cc 4
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class ProductOfArrayExceptSelf
8
{
9
    public static function productExceptSelf(array $nums): array
10
    {
11
        if (empty($nums)) {
12
            return [];
13
        }
14
        $n = count($nums);
15
        $ans = $left = $right = array_fill(0, $n, 0);
16
        $left[0] = $right[$n - 1] = 1;
17
18
        for ($i = 1; $i < $n; $i++) {
19
            $left[$i] = $left[$i - 1] * $nums[$i - 1];
20
        }
21
        for ($i = $n - 2; $i >= 0; $i--) {
22
            $right[$i] = $right[$i + 1] * $nums[$i + 1];
23
        }
24
        for ($i = 0; $i < $n; $i++) {
25
            $ans[$i] = $left[$i] * $right[$i];
26
        }
27
28
        return $ans;
29
    }
30
31
    public static function productExceptSelf2(array $nums): array
32
    {
33
        if (empty($nums)) {
34
            return [];
35
        }
36
        $n = count($nums);
37
        $ans = array_fill(0, $n, 0);
38
        for ($i = 0, $tmp = 1; $i < $n; $i++) {
39
            $ans[$i] = $tmp;
40
            $tmp *= $nums[$i];
41
        }
42
        for ($i = $n - 1, $tmp = 1; $i >= 0; $i--) {
43
            $ans[$i] *= $tmp;
44
            $tmp *= $nums[$i];
45
        }
46
47
        return $ans;
48
    }
49
}
50