Skip to content

Instantly share code, notes, and snippets.

@gabhi
Last active August 29, 2015 14:03
Show Gist options
  • Save gabhi/00f49c93ba0a2c917546 to your computer and use it in GitHub Desktop.
Save gabhi/00f49c93ba0a2c917546 to your computer and use it in GitHub Desktop.
three sum java code
import java.util.Arrays;
public class tsum {
public static void main(String[] args) {
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 19;
boolean t = threeSumTo(A, sum);
System.out.println(t);
}
public static boolean threeSumTo(int[] array, int x) {
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
boolean result = twoSumTo(array, x - array[i], i);
if (result) {
return result;
}
}
return false;
}
private static boolean twoSumTo(int[] array, int x, int low) {
int high = array.length - 1;
while (low < high) {
if (array[low] + array[high] == x) {
return true;
}
if (array[low] + array[high] > x) {
high--;
} else {
low++;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment