Created
June 6, 2022 19:42
-
-
Save sudofox/cfa3ba54ab4d34215bfe5fa908b5df85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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