Skip to content

Instantly share code, notes, and snippets.

@slav123
Created April 26, 2020 08:16
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 slav123/1af4c7406e6999cd9995f5aa52b9c795 to your computer and use it in GitHub Desktop.
Save slav123/1af4c7406e6999cd9995f5aa52b9c795 to your computer and use it in GitHub Desktop.
threeSum optimised
<?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