-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFairCandySwap.php
46 lines (40 loc) · 1.07 KB
/
FairCandySwap.php
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
<?php
declare(strict_types=1);
namespace leetcode;
class FairCandySwap
{
public static function fairCandySwap(array $a, array $b): array
{
if (empty($a) || empty($b)) {
return [];
}
[$aSum, $bSum] = [array_sum($a), array_sum($b)];
$dif = (int) (($aSum - $bSum) / 2);
for ($i = 0, $m = count($a); $i < $m; $i++) {
for ($j = 0, $n = count($b); $j < $n; $j++) {
if ($a[$i] - $b[$j] === $dif) {
return [$a[$i], $b[$j]];
}
}
}
return [];
}
public static function fairCandySwap2(array $a, array $b): array
{
if (empty($a) || empty($b)) {
return [];
}
[$map, $dif] = [[], (int) ((array_sum($a) - array_sum($b)) / 2)];
foreach ($a as $v) {
if (!isset($map[$v])) {
$map[$v] = $v;
}
}
foreach ($b as $v) {
if (isset($map[$dif + $v])) {
return [$dif + $v, $v];
}
}
return [];
}
}