Given two sorted arrays of integers, a
and b
, and an integer c
, I have to find i,j
such that:
a[i] + b[j]
I think you dont have to search the whole array b[] next time.......u have to search in between starting of array b and the lowest bound u found till now....for the next element in a[].It would definitely reduce your time complexity...and when u find the given target 'c' you must stop your search.
The below solution is in linear Time Complexity O(n), Space Complexity O(1)
public class ClosestPair {
public static void main(String[] args)
{
int ar2[] = {4, 5, 7};
int ar1[] = {10, 20, 30, 40};
int x = 10 ;
closest(ar1,ar2,x);
}
public static void closest(int[] ar1, int[] ar2, int x)
{ int diff=Integer.MAX_VALUE;
int first_num=0;
int second_num=0;
int second_diff=Integer.MAX_VALUE;
for(int i=0; i<ar1.length; i++)
{
if(x==ar1[i] )
{
System.out.println("no pair possible");
return;
}
}
for(int i=0; i<ar2.length; i++)
{
if(x==ar2[i])
{
System.out.println("no pair possible");
return;
}
}
for(int i=0; i<ar2.length; i++)
{
if(Math.abs(x-ar2[i])<=diff)
{
diff=Math.abs(x-ar2[i]);
first_num=ar2[i];
}
}
diff=x-first_num;
for(int i=0; i<ar1.length; i++)
{
if(Math.abs(diff-ar1[i])<=second_diff)
{
second_diff= Math.abs(diff-ar1[i]);
second_num= ar1[i];
}
}
System.out.println(first_num + " "+ second_num);
}
}
Thinking a bit about it, then you could ask yourself:
"Is it necessary, each time, to search in the sorted b-array for successive values from a[]?"