3sum problem. solution is O(N^2)
/**
* given an integer array and a target k return boolean value if any distinct three elements from the array sums up to k.
*/
public class ThreeSumProblem {
public static boolean threeSum(int[] arr, int k) {
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
if (i == start || arr[start] + arr[end] + arr[i] < k)
start++;
else if (end == i || arr[start] + arr[end] + arr[i] > k)
end--;
else
return true;
}
}
return false;
}
public class ThreeSumProblemTest extends TestCase {
@Test
public void testThreeSum() throws Exception {
assertTrue(ThreeSumProblem.threeSum(new int[]{3,5,1,5,32,34,5,6,85} , 15));
assertFalse(ThreeSumProblem.threeSum(new int[]{3, 5, 1, 5, 32, 34, 5, 6, 85}, 8));
assertTrue(ThreeSumProblem.threeSum(new int[]{3,5,1,5,32,34,5,6,-85} , -75));
assertTrue(ThreeSumProblem.threeSum(new int[]{3,5,1,5,32,34,5,6,85} , 151));
assertFalse(ThreeSumProblem.threeSum(new int[]{3, 5, 1, 5, 32, 34, 5, 6, 85}, 152));
assertTrue(ThreeSumProblem.threeSum(new int[]{0,0,0,0,0} , 0));
assertFalse(ThreeSumProblem.threeSum(new int[]{0} , 0));
assertFalse(ThreeSumProblem.threeSum(new int[]{0,0} , 0));
assertTrue(ThreeSumProblem.threeSum(new int[]{0, 0, 0}, 0));
}
}
}