Given two sorted array in non-descending order, each contains positive integers
The distance is define as following
pick up a number from each array, compute their difference
return the shortest distance among them-that's the distance between the two arrays
example
int[] a = {1, 3, 5, 7 , 9} ;
int[] b = {2, 4, 8} ;
The result is 1
Code
1 public int Distance(int[] a, int[] b)
2 {
3 int d = int.MaxValue;
4 int i = 0;
5 int j = 0;
6 while (i < a.Length && j < b.Length)
7 {
8 if (a[i] < b[j])
9 {
10 d = Math.Min(d, Math.Abs(a[i] - b[j]));
11 i++;
12 }
13 else if (a[i] == b[j])// note, 0 is the shortest distance of all
14 return 0; // if we got 0, no need to test the subsequent values, return immediately
15 else
16 {
17 d = Math.Min(d, Math.Abs(a[i] - b[j]));
18 j++;
19 }
20 }
21 return d;
22 }