fork(1) download
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. class Main
  5. {
  6. public static void main (String[] args) throws java.lang.Exception
  7. {
  8. int a[]={4,1,2,7,9,3};
  9. int length=a.length;
  10. length--;
  11. mergesort(a,0,length);
  12. if(SumToTarget(a,0,length,4)==1)
  13. System.out.println("Duplicates exist in the array");
  14. else
  15. System.out.println("Duplicates does not exist in the array");
  16. }
  17.  
  18. /* Function to check whether the duplicates whose sum equal to target num exist or not */
  19. public static int SumToTarget(int a[],int start,int last , int num)
  20. {
  21. int first_index=start;
  22. int last_index=last;
  23. /*if first_index becomes greater than last_index it means duplicates does not exist */
  24. while(first_index<last_index)
  25. {
  26. /* if sum of dupliactes is equal to required sum it means duplicates are present hence returning 1 */
  27. if((a[first_index]+a[last_index])==num )
  28. {
  29. System.out.println("Two numbers are:->"+a[first_index]+" "+a[last_index]);
  30. return 1;
  31.  
  32. }
  33. /*if sum of two number is greater than the required sum then the last_index will be decreased*/
  34. else if((a[first_index]+a[last_index])>num)
  35. {
  36. last_index--;
  37. }
  38. /*if sum of two number is less than the required sum then the first_index will be increased*/
  39. else if((a[first_index]+a[last_index])<num)
  40. {
  41. first_index++;
  42. }
  43. }
  44.  
  45. /*program will reach here only if dupliactes consequently will return 0 */
  46. return 0;
  47. }
  48.  
  49. public static void mergesort(int a[],int start,int last)
  50. {
  51. if(start<last)
  52. {
  53. int mid=(start+last)/2;
  54. mergesort(a,start,mid);
  55. mergesort(a,mid+1,last);
  56. merge(a,start,last,mid);
  57. }
  58. }
  59. public static void merge(int a[],int start ,int last,int mid )
  60. {
  61. int j,k,l;
  62. int c[]=new int[a.length];
  63. j=start;
  64. k=start;
  65. l=mid+1;
  66. while(j<=mid && l<=last )
  67. {
  68. if(a[j]<a[l])
  69. {
  70. c[k]=a[j];
  71. k++;
  72. j++;
  73. }
  74. else
  75. {
  76. c[k]=a[l];
  77. k++;
  78. l++;
  79. }
  80. }
  81. while(j<=mid)
  82. {
  83. c[k]=a[j];
  84. k++;
  85. j++;
  86. }
  87. while(l<=last)
  88. {
  89. c[k]=a[l];
  90. k++;
  91. l++;
  92. }
  93.  
  94. for(int i=start;i<=k-1;i++)
  95. {
  96. a[i]=c[i];
  97. }
  98. }
  99. }
  100.  
Success #stdin #stdout 0.07s 381184KB
stdin
Standard input is empty
stdout
Two numbers are:->1 3
Duplicates exist in the array