-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find the closest pair from two arrays
61 lines (35 loc) · 1.2 KB
/
Find the closest pair from two arrays
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//User function Template for Java
class Solution{
// Function for finding maximum and value pair
public static ArrayList<Integer> printClosest (int arr[], int brr[], int n, int m, int x)
{
// code here
int dummy = n;
n = m;
m = dummy;
ArrayList<Integer> result = new ArrayList<>();
int diff = Integer.MAX_VALUE;
int pointerA =0, pointerB = 0;
int left = 0, right= n-1;
while(left < m && right>=0)
{
if(Math.abs(arr[left] + brr[right] - x) < diff)
{
pointerA = left;
pointerB = right;
diff = Math.abs(arr[left] + brr[right] - x);
}
if(arr[left] + brr[right] > x)
{
right--;
}
else
{
left++;
}
}
result.add(arr[pointerA]);
result.add(brr[pointerB]);
return result;
}
}