Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created November 9, 2013 15:28
Show Gist options
  • Save ylegall/7386596 to your computer and use it in GitHub Desktop.
Save ylegall/7386596 to your computer and use it in GitHub Desktop.
find 3 elements of an unsorted array whose sum is 0.
import std.stdio;
import std.typecons;
alias Tuple!(int, int) Pair;
// O(n^2)
auto triple(int[] array) {
Pair[int] map;
for (int j = 1; j < array.length-1; ++j) {
for (int i = 0; i < j; ++i) {
map[array[i] + array[j]] = tuple(i,j);
}
for (int k = j + 1; k < array.length; ++k) {
if (-array[k] in map) {
auto p = map[-array[k]];
return tuple(array[p[0]], array[p[1]], array[k]);
}
}
}
return tuple(-1,-1,-1);
}
void main() {
auto array = [1,7,-2,6,-1,8,-9,3,4,-5];
writeln(triple(array));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment