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

IntersectionOfTwoArraysII   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 14
eloc 27
c 1
b 0
f 0
dl 0
loc 44
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B intersect() 0 18 7
B intersect2() 0 22 7
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