Created
May 5, 2022 17:18
-
-
Save bmcculley/37fb8bc183f59b9d45a4eaf8995a1a73 to your computer and use it in GitHub Desktop.
Quick solution to the Two Sum Problem in PHP
This file contains hidden or 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 | |
// 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