FindPivotIndex   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A pivotIndex2() 0 14 4
A pivotIndex3() 0 16 5
A pivotIndex() 0 15 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class FindPivotIndex
8
{
9
    public static function pivotIndex(array $nums): int
10
    {
11
        if (empty($nums)) {
12
            return 0;
13
        }
14
        [$left, $right] = [0, array_sum($nums)];
15
        foreach ($nums as $key => $num) {
16
            $right -= $num;
17
            if ($left === $right) {
18
                return $key;
19
            }
20
            $left += $num;
21
        }
22
23
        return -1;
24
    }
25
26
    public static function pivotIndex2(array $nums): int
27
    {
28
        if (empty($nums)) {
29
            return 0;
30
        }
31
32
        [$n, $sum, $total] = [count($nums), 0, array_sum($nums)];
33
        for ($i = 0; $i < $n; $sum += $nums[$i++]) {
34
            if ($sum * 2 === $total - $nums[$i]) {
35
                return $i;
36
            }
37
        }
38
39
        return -1;
40
    }
41
42
    public static function pivotIndex3(array $nums): int
43
    {
44
        if (empty($nums)) {
45
            return 0;
46
        }
47
        [$n, $sum, $total] = [count($nums), 0, array_sum($nums)];
48
        for ($i = 0; $i < $n; $i++) {
49
            if ($i !== 0) {
50
                $sum += $nums[$i - 1];
51
            }
52
            if ($total - $sum - $nums[$i] === $sum) {
53
                return $i;
54
            }
55
        }
56
57
        return -1;
58
    }
59
}
60