Created
April 26, 2020 08:16
-
-
Save slav123/1af4c7406e6999cd9995f5aa52b9c795 to your computer and use it in GitHub Desktop.
threeSum optimised
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 | |
* @return Integer[][] | |
*/ | |
function threeSum($nums) { | |
$results = []; | |
$max = count($nums); | |
sort($nums); | |
for ($a = 0;$a < $max;$a++) { | |
$first = $nums[$a]; | |
$m = []; | |
for ($b = $a+1;$b < $max;$b++) { | |
$second = $nums[$b]; | |
if (array_key_exists($second, $m)) { | |
$match = [$first, $second, $nums[$m[$second]]]; | |
if (array_search($match, $results, TRUE) === FALSE) { | |
$results[] = $match; | |
} | |
} else { | |
$m[-($first+$second)] = $b; | |
} | |
} | |
} | |
return $results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment