Skip to content

Instantly share code, notes, and snippets.

@sudofox
Created June 6, 2022 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudofox/cfa3ba54ab4d34215bfe5fa908b5df85 to your computer and use it in GitHub Desktop.
Save sudofox/cfa3ba54ab4d34215bfe5fa908b5df85 to your computer and use it in GitHub Desktop.
<?php
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
foreach ($nums as $i => $number) {
$searchArea = $nums;
unset($searchArea[$i]);
$desired = $target - $number;
if (!in_array($desired, $searchArea)) {
continue;
}
return [$i, array_search($desired, $searchArea)];
}
return [];
}
function verify($nums, $target, $expected) {
$result = $this->twoSum($nums, $target);
if ($result != $expected) {
echo "FAIL: Expected [" . implode(", ", $expected) . "] but got [" . implode(", ", $result) . "]\n";
} else {
echo "PASS: Expected [" . implode(", ", $expected) . "] and got [" . implode(", ", $result) . "]\n";
}
}
}
$a = new Solution();
// test cases
// basic
echo "=== Basic ===\n";
$a->verify([2, 7, 11, 15], 9, [0, 1]);
// not first two
echo "=== Not first two ===\n";
$a->verify([2, 7, 11, 15], 18, [1, 2]);
//negatives
echo "=== Negatives ===\n";
$a->verify([-2, -7, 11, 15], -9, [0, 1]);
// very large numbers
echo "=== Very large ===\n";
$a->verify([2147483647, 2147483647, 2147483647, 1], 2147483648, [0, 3]);
// very large numbers, but negative
echo "=== Very large negative ===\n";
$a->verify([-2147483647, -2147483000, -2147483641, -1], -2147483648, [0, 3]);
// impassable test case
echo "=== Impassable ===\n";
$a->verify([2147483647, 2147483647, 2147483647, 1], 2147483649, [0, 3]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment