Hey Guys!
Hope you all doing well.
Felt like utilizing a boring day by dusting up my coding skills.
I found a practice code scenario from GeeksForGeeks Portal and solved it myself.
I believe in power of "Knowledge shared = Knowledge²". So, just gear up to see what I got for you today.
* Practice Question 1: Find the closest pair from two sorted array for given element
* Language Used: Java
* Difficulty Level: Medium
* Time Complexity: O(n)
* Example 1:
* Input:
10 20 30 40
1 4 5 7
38
* Output:
30 and 7
* Example 2:
* Input:
1 4 5 7
10 20 30 40
38
* Output:
7 and 30
Let's gear up to reveal the solution.
/**
* @author BloggerMonz
**/
import java.util.Scanner;
public class ClosePair {
public String FindPair(int[] a, int[] b, int x)
{
String output;
int aLen = a.length-1;
int bLen = b.length-1;
int temp, tempRes, pairA=0, pairB=0,Res = x+1;
if(b[bLen]>a[aLen])
{
for(int i=bLen;i>=0;i--)
{
for(int j=0;j<=aLen;j++)
{
temp = b[i]+a[j];
tempRes = (temp>x)? temp-x : x-temp;
if(tempRes<Res)
{
Res = tempRes;
pairA = a[j];
pairB = b[i];
}
if(temp > x)
break;
}
}
}
else
{
for(int i=aLen;i>=0;i--)
{
for(int j=0;j<=bLen;j++)
{
temp = a[i]+b[j];
tempRes = (temp>x)? temp-x : x-temp;
if(tempRes<Res)
{
Res = tempRes;
pairA = a[i];
pairB = b[j];
}
if(temp > x)
break;
}
}
}
output = Integer.toString(pairA)+" and "+ Integer.toString(pairA);
return output;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String s1[] = sc.nextLine().split(" ");
int arr1[] = new int[s1.length];
String s2[] = sc.nextLine().split(" ");
int arr2[] = new int[s2.length];
String sx = sc.nextLine();
int x = Integer.parseInt(sx);
for(int i=0;i<s1.length;i++)
arr1[i]=Integer.parseInt(s1[i]);
for(int i=0;i<s2.length;i++)
arr2[i]=Integer.parseInt(s2[i]);
ClosePair cp = new ClosePair();
var result = cp.FindPair(arr1,arr2,x);
System.out.println(result);
}
}
Console:
If you got any alternate solution or thoughts/queries share in the below comment section. Don't forget to subscribe Letsgobeyondvision 🎕
Stay safe and have a great day!
Comments
Post a Comment