Test Failed
Push — master ( b4e369...01c2bc )
by Jinyun
11:59
created

IntersectionOfTwoArraysII::intersect()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 18
rs 8.8333
cc 7
nc 7
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class IntersectionOfTwoArraysII
8
{
9
    public static function intersect(array $p, array $q): array
10
    {
11
        if (empty($p) || empty($q)) {
12
            return [];
13
        }
14
        $ans = $map = [];
15
        foreach ($p as $v) {
16
            $map[$v] = ($map[$v] ?? 0) + 1;
17
        }
18
19
        foreach ($q as $v) {
20
            if (isset($map[$v]) && $map[$v]-- > 0) {
21
                array_push($ans, $v);
22
            }
23
        }
24
        sort($ans);
25
26
        return $ans;
27
    }
28
29
    public static function intersect2(array $p, array $q): array
30
    {
31
        if (empty($p) || empty($q)) {
32
            return [];
33
        }
34
        sort($p);
35
        sort($q);
36
        [$ans, $m, $n] = [[], count($p), count($q)];
37
        $i = $j = 0;
38
        while ($i < $m && $j < $n) {
39
            if ($p[$i] > $q[$j]) {
40
                $j++;
41
            } elseif ($p[$i] < $q[$j]) {
42
                $i++;
43
            } else {
44
                array_push($ans, $p[$i]);
45
                $i++;
46
                $j++;
47
            }
48
        }
49
50
        return $ans;
51
    }
52
}
53