-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProductOfArrayExceptSelf.php
More file actions
49 lines (42 loc) · 1.12 KB
/
ProductOfArrayExceptSelf.php
File metadata and controls
49 lines (42 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
declare(strict_types=1);
namespace leetcode;
class ProductOfArrayExceptSelf
{
public static function productExceptSelf(array $nums): array
{
if (empty($nums)) {
return [];
}
$n = count($nums);
$ans = $left = $right = array_fill(0, $n, 0);
$left[0] = $right[$n - 1] = 1;
for ($i = 1; $i < $n; $i++) {
$left[$i] = $left[$i - 1] * $nums[$i - 1];
}
for ($i = $n - 2; $i >= 0; $i--) {
$right[$i] = $right[$i + 1] * $nums[$i + 1];
}
for ($i = 0; $i < $n; $i++) {
$ans[$i] = $left[$i] * $right[$i];
}
return $ans;
}
public static function productExceptSelf2(array $nums): array
{
if (empty($nums)) {
return [];
}
$n = count($nums);
$ans = array_fill(0, $n, 0);
for ($i = 0, $tmp = 1; $i < $n; $i++) {
$ans[$i] = $tmp;
$tmp *= $nums[$i];
}
for ($i = $n - 1, $tmp = 1; $i >= 0; $i--) {
$ans[$i] *= $tmp;
$tmp *= $nums[$i];
}
return $ans;
}
}