Title Description:
Known three ascending integer arrays A[l], b[m] and c[n]. Find an element in each of the three arrays to minimize the distance between the three triples.
The distance definition for triples is: Suppose A[i], b[j], and C[k] is a ternary group, then the distance is: Distance = max (|a[i]–b[j]|,|a[i]–c[k]|,|b[j]–c[k]|) Please design an optimal algorithm to find the minimum distance of ternary group , and analyze the complexity of time.
Key formula: Max (|a[i]–b[j]|,|a[i]–c[k]|,|b[j]–c[k]|) = (ABS (A[i]-b[j]) +abs (A[i]-c[k]) +abs (b[j]-c[k))/2
Ideas:
Method One
Violence law, three-layer cycle, Time complexity O (l*m*n)
method Two: Minimum distance method
Assuming that the elements in the three arrays currently traversed are a[i],b[j],c[k] and have a[i]<=b[j]<=c[k], the minimum distance is certainly d = c[k]-a[i], then there are three cases:
- Next A[i],b[j],c[k+1] The minimum distance, because c[k+1]>=c[k], so the minimum distance at this time is c[k+1]-a[i], certainly greater than D
- Next A[i],b[j+1],c[k] The minimum distance, if b[j+1]<=c[k], then the minimum distance is unchanged, if b[j+1]>c[k], at this time the minimum distance is b[j+1]-a[i], the same, is certainly greater than D
- The minimum distance for the next a[i],b[j+1],c[k], if a[i+1] < C[k] + (C[k]-a[i]), the minimum distance at this time is obviously less than D.
Therefore, each time we add the index of the smallest element to 1, it is possible to make the minimum distance more optimal. So, the whole idea is to start with the minimum distance of the first element of the three array, then move the subscript of the smallest element in the smallest three elements, compare it with the minimum distance previously obtained, and see if the minimum distance needs to be updated until three arrays are traversed, and the time complexity is O (l+m+n)
1 Public Static intMindistance (int[] A,int[] B,int[] c) {2 intCurdis = 0 ;3 intMin = 0 ;4 intMindis =Integer.min_value;5 inti = 0 ;6 intj = 0 ;7 intK = 0 ;8 9 while(I < A.length && J < b.length && K <c.length) {TenCurdis = Max (Math.Abs (A[i]-b[j]), Math.Abs (A[i]-c[k]), Math.Abs (b[j]-C[k])) ; One if(Curdis <Mindis) { AMindis =Curdis; - } - theMin =min (a[i], b[j], c[k]); - if(min = =A[i]) { -i++ ; -}Else if(min = =B[j]) { +J + + ; -}Else{ +k++ ; A } at } - returnMindis; - } - - Private Static intMaxintAintBintc) { - intmax = a > B?a:b; inmax = max > c?Max:c; - returnMax; to } + - Private Static intMinintAintBintc) { the intMin = a < b?a:b; *min = min < c?Min:c; $ returnmin;Panax Notoginseng}
How to find the minimum distance of ternary group