Created
November 9, 2013 15:28
-
-
Save ylegall/7386596 to your computer and use it in GitHub Desktop.
find 3 elements of an unsorted array whose sum is 0.
This file contains hidden or 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
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