Skip to content

Instantly share code, notes, and snippets.

@bmcculley
Created May 5, 2022 17:18
Show Gist options
  • Save bmcculley/37fb8bc183f59b9d45a4eaf8995a1a73 to your computer and use it in GitHub Desktop.
Save bmcculley/37fb8bc183f59b9d45a4eaf8995a1a73 to your computer and use it in GitHub Desktop.
Quick solution to the Two Sum Problem in PHP
<?php
// https://leetcode.com/problems/two-sum/
function solution($nums, $target) {
$memo = array();
for ($i = 0; $i < count($nums); $i++) {
$key = $target - $nums[$i];
if (array_key_exists($nums[$i], $memo)) {
return array($memo[$nums[$i]], $i);
} else {
$memo[$key] = $i;
}
}
return -1;
}
function test_case_one() {
$nums = array(2,7,11,15);
$target = 9;
$expected = array(0,1);
$rv = solution($nums, $target);
print_r($rv);
if ($expected == $rv) {
print("\nTrue\n");
} else{
print("\nFalse\n");
}
}
test_case_one();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment