fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. new Ideone().run();
  13. }
  14.  
  15. void run(){
  16. int[] arr = { 1, 2, 3, 4, 5, 6 };
  17. int req = 14;
  18. // For the algorithm to work correctly, the array must be sorted
  19. Arrays.sort(arr);
  20.  
  21. for(int i=0; i<arr.length; i++){// Iterate over the elements of the array.
  22.  
  23. // Check in linear time whether there exists distinct indices
  24. // lo and hi that sum to req-arr[i]
  25. int lo = 0;
  26. int hi = arr.length-1;
  27. boolean found = false;
  28. while(lo<hi){
  29. if(lo==i){
  30. lo++;
  31. continue;
  32. }
  33. if(hi==i){
  34. hi--;
  35. continue;
  36. }
  37. int val = arr[lo] + arr[hi] + arr[i];
  38. if(val == req){
  39. System.out.println(arr[lo] + " + " + arr[hi] + " + " + arr[i] + " = " + req);
  40. found = true;
  41. break;
  42. }else if(val < req){
  43. lo++;
  44. }else{
  45. hi--;
  46. }
  47. }
  48. if(found){
  49. break;
  50. }
  51. }
  52. }
  53. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
5 + 6 + 3 = 14