Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@slav123
Last active April 26, 2020 08:15
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/32bb0d3c31287aeade4cb47045fb9e58 to your computer and use it in GitHub Desktop.
Save slav123/32bb0d3c31287aeade4cb47045fb9e58 to your computer and use it in GitHub Desktop.
threes sum brutforce
<?php
function threeSum($nums) {
$results = [];
$max=count($nums);
sort($nums);
print_r($nums);
for ($a = 0;$a < $max;$a++) {
$first = $nums[$a];
for ($b = $a+1; $b<$max; $b++) {
$second = $nums[$b];
$match = -($first+$second);
var_dump($match);
echo "{$first};{$second} =>";
echo $match . PHP_EOL;
$slice = array_slice($nums, $b);
echo join(':', $slice) . PHP_EOL;
$third_pos = array_search($match, $slice, TRUE);
if ($third_pos !== FALSE) {
if (array_search([$first, $second, $slice[$third_pos]], $results, TRUE) === FALSE) {
$results[] = [$first, $second, $slice[$third_pos]];
}
}
}
}
return $results;
}
print_r(threeSum([0,0,0]));
//print_r(threeSum([-1, 0, 1, 2, -1, -4]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment