Skip to content

Instantly share code, notes, and snippets.

@st0le
Last active January 23, 2018 19:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st0le/5893435 to your computer and use it in GitHub Desktop.
Save st0le/5893435 to your computer and use it in GitHub Desktop.
O(n^2 logn) solution to 3SUM
// Complexity - O(n^2 logn)
private int[] findTriple_2(int[] A) {
Arrays.sort(A); // O(nlogn)
for (int i = 0, l = A.length; i < l && A[i] < 0; i++) { //O(n^2 logn)
for (int j = i + 1; j < l && A[i] + A[j] < 0; j++) {
int k = Arrays.binarySearch(A, j + 1, l, -A[i] - A[j]);
if (k > j) return new int[]{A[i], A[j], A[k]};
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment