-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountPairsWithGivenSum.php
55 lines (43 loc) · 1.17 KB
/
CountPairsWithGivenSum.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
47
48
49
50
51
52
53
54
55
<?php
declare(strict_types=1);
namespace Fathom\Leetcode\Easy;
/*
* Given an array of integers, and a number ‘sum’, print all pairs in the array whose sum is equal to ‘sum’.
*/
class CountPairsWithGivenSum
{
public static function getPairs(array $nums, int $target): array
{
$res = [];
for ($i = 0, $iMax = count($nums); $i < $iMax; $i++) {
for ($j = $i +1, $jMax = count($nums); $j < $jMax; $j++) {
if ($nums[$i] + $nums[$j] === $target) {
$res[] = [$nums[$i], $nums[$j]];
}
}
}
return $res;
}
public static function getPairs2(array $nums, int $target): array
{
sort($nums, SORT_NUMERIC);
$res = [];
$i = 0;
$j = count($nums) - 1;
while ($i < $j) {
$sum = $nums[$i] + $nums[$j];
if ($sum === $target) {
$res[] = [$nums[$i], $nums[$j]];
$i++;
$j--;
continue;
}
if ($sum < $target) {
$i++;
} else {
$j--;
}
}
return $res;
}
}