Skip to content

Instantly share code, notes, and snippets.

@andreytwostep
Created September 23, 2017 21:19
Show Gist options
  • Save andreytwostep/11720cbb28302936d48366004b7ab5d9 to your computer and use it in GitHub Desktop.
Save andreytwostep/11720cbb28302936d48366004b7ab5d9 to your computer and use it in GitHub Desktop.
function binarySearchRecursiveImpl(array $array, $find, $left, $right) {
if (count($array) < 1 || $left > $right) {
return -1;
}
$mid = floor(($left + $right) / 2);
if ($find == $array[$mid]) {
return $mid;
}
return $find > $array[$mid] ?
binarySearchRecursiveImpl($array, $find, $mid+1, $right) :
binarySearchRecursiveImpl($array, $find, $left, $mid-1);
}
function threeSumN2logn($data) {
$count = 0;
if (count($data) < 3) {
return $count;
}
for ($i = 0; $i < count($data); $i++) {
for ($j = $i+1; $j < count($data); $j++) {
$lookup = ((int) $data[$i] + (int) $data[$j]) * -1;
$mid = binarySearchRecursiveImpl($data, $lookup, $j+1, count($data)-1);
if ($mid >= 0) {
$count++;
}
}
}
return $count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment