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

ProductOfArrayExceptSelf   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 24
c 1
b 0
f 0
dl 0
loc 41
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A productExceptSelf2() 0 17 4
A productExceptSelf() 0 20 5
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