[Classic Interview Questions] [Alibaba] the minimum distance between the productkey, devicename, and devicesecret.
Question
Three ascending integer arrays a [l], B [m], and c [n] are known. Find an element in each of the three arrays. The distance between the elements is the minimum. Assume that a [I], B [j], and c [k] are a triplet, the distance is:
Distance = max (| a [I]-B [j] |, | a [I]-c [k] |, | B [j]-c [k] |)
Design an Optimal Algorithm for Finding the minimum triples distance and analyze the time complexity.
Ideas
Keep the index I, j, k with three subscripts, and find the smallest elements in a [I], B [j], and c [k. If a [I] is the smallest, the next cycle I = I + 1, and the other two indexes remain unchanged. If B [j] is the smallest, the next cycle j = j + 1, and the other two indexes remain unchanged. If c [k] is the smallest, k = k + 1 in the next cycle, and the other two indexes remain unchanged. This loop ends until the subscript corresponding to the minimum number reaches the end of the array. Minimum record distance.
Time Complexity: O (l + m) (each cycle always has a subscript step ).
Code
/* ------------------------------------------- * Date: 2015-02-21 * Author: SJF0115 * Subject: minimum distance of Triplet * Source: Ali * blog: ------------------------------------------- */# include <iostream> # include <climits> # include <algorithm> using namespace std; class Solution {public: int MinDistance (int a [], int l, int B [], int m, int c [], int n) {if (l <= 0 | n <= 0 | m <= 0) {return-1;} // if int min = INT_MAX; int dis = 0, first = 0, second = 0, third = 0; for (int I = 0, j = 0, k = 0; I <l & j <m & k <n ;) {dis = max (abs (a [I]-B [j]), abs (a [I]-c [k]), abs (B [j]-c [k]); if (dis <min) {min = dis; first = I; second = j; third = k ;} // if (a [I] <B [j]) {if (a [I] <c [k]) {++ I ;} // if else {++ k;} // else} // if else {if (B [j] <c [k]) {++ j ;} // if else {++ k ;} // else} // for cout <"First->" <first <"Second->" <second <"Third->" <<third <endl; return min ;}; int main () {Solution solution; int a [] = {5, 16, 20}; int B [] = {13, 14, 15, 17, 35 }; int c [] = {19,22, 24,29, 32,42}; int l = 3, m = 5, n = 6; int result = solution. minDistance (a, l, B, m, c, n); cout <result <endl ;}
If you have a good idea, you can leave a message .....