fork download
  1. import java.util.*;
  2. class MainClass {
  3. public static void main(String[] args) {
  4. int[] a = {0, 0, 0};
  5. System.out.println(((Object) isThreeSumEqualsTarget(a, 0)).toString());
  6. }
  7.  
  8. public static boolean isThreeSumEqualsTarget(int[] array, int targetNumber) {
  9.  
  10. //O(n log (n))
  11. Arrays.sort(array);
  12. System.out.println(Arrays.toString(array));
  13.  
  14. int leftIndex = 0;
  15. int rightIndex = array.length - 1;
  16.  
  17. //O(n)
  18. while (leftIndex + 1 < rightIndex - 1) {
  19. //take sum of two corners
  20. int sum = array[leftIndex] + array[rightIndex];
  21. //find if the number matches exactly. Or get the closest match.
  22. //here i am not storing closest matches. You can do it for yourself.
  23. //O(log (n)) complexity
  24. int binarySearchClosestIndex = binarySearch(leftIndex + 1, rightIndex - 1, targetNumber - sum, array);
  25. //if exact match is found, we already got the answer
  26. if (-1 == binarySearchClosestIndex) {
  27. System.out.println(("combo is " + array[leftIndex] + ", " + array[rightIndex] + ", " + (targetNumber - sum)));
  28. return true;
  29. }
  30. //if exact match is not found, we have to decide which pointer, left or right to move inwards
  31. //we are here means , either we are on left end or on right end
  32. else {
  33.  
  34. //we ended up searching towards start of array,i.e. we need a lesser sum , lets move inwards from right
  35. //we need to have a lower sum, lets decrease right index
  36. if (binarySearchClosestIndex == leftIndex + 1) {
  37. rightIndex--;
  38. } else if (binarySearchClosestIndex == rightIndex - 1) {
  39. //we need to have a higher sum, lets decrease right index
  40. leftIndex++;
  41. }
  42. }
  43. }
  44. return false;
  45. }
  46.  
  47. public static int binarySearch(int start, int end, int elem, int[] array) {
  48. int mid = 0;
  49. while (start <= end) {
  50. mid = (start + end) >>> 1;
  51. if (elem < array[mid]) {
  52. end = mid - 1;
  53. } else if (elem > array[mid]) {
  54. start = mid + 1;
  55. } else {
  56. //exact match case
  57. //Suits more for this particular case to return -1
  58. return -1;
  59. }
  60. }
  61. return mid;
  62. }
  63. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
[0, 0, 0]
false