今天早上在Quora上看到的一个题目,很不错的!最直观的是枚举n^3,但稍微进步一点的观察是找出3个数,然后最大的减去最小的2倍的结果,然后就有了线性扫一遍就OK。
Given three arrays, A, B, and C, what is the best algorithm to find the minimum value of , where ?
解答:
Assuming that the arrays are not sorted, here is an algorithm.
1. Sort the arrays A, B and C. Let there sizes be n,m and p.
2. let i,j,k =0 points to the start indices of the 3 arrays.
3. ans = INT_MAX;
4. while(i < n && j<m && k<p)
ans = min(ans, abs(A[i] - B[j]) + abs(B[j] - C[k]) + abs(C[k]-A[i]))
increment the index of minumum of A[i], B[j], C[k]
5. return ans;
Sorting takes nlogn time. If the arrays are alread sorted, it would be an O(n) algo.