O(1) 的小乐
豆瓣账号:http://www.douban.com/people/sosisarah/

今天早上在Quora上看到的一个题目,很不错的!最直观的是枚举n^3,但稍微进步一点的观察是找出3个数,然后最大的减去最小的2倍的结果,然后就有了线性扫一遍就OK。

Given three arrays, A, B, and C, what is the best algorithm to find the minimum value of |a - b| + |b - c| + |c - a|, where  a \in A, b \in B, c \in C?

解答:

Assuming that the arrays are not sorted, here is an nlogn 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.

posted on 2014-04-18 13:13  O(1)的小乐  阅读(281)  评论(2编辑  收藏  举报