這裏用C陰涼溶液(++)
int a[3], b[3]; /* the two arrays */
int c[4]; /* target */
int s=0, t=0, k;
int i;
for (i=0;i<3;i++) { k = a[i]-b[i]; s += k; t += k*(a[i]+b[i]); }
/* At this point s is the difference of the two distinct elements
and t is the difference of their squares, i.e. s = x - y and t = x^2 - y^2
because (x-y)(x+y) = x^2-yx+yx-y^2 = x^2-y^2
Because the two elements are distinct, s != 0 and we can easily divide t
by s to get (x + y), from which then we have
s == x - y
t == x + y
i.e. x = (s+t)/2 and y=(t-s)/2 */
t /= s;
int x = (s + t)/2;
int y = (t - s)/2;
/* Now x, y are the distinct elements, x from array a and y from array b */
/* Fill in the results */
c[0] = x;
c[3] = y;
/* If a[0] is non-shared, then a[1] must be the first shared element; otherwise a[0] */
c[1] = (a[0] == x ? a[1] : a[0]);
/* If a[2] is non-shared, then a[1] must be the last shared element; otherwise a[2] */
c[2] = (a[2] == x ? a[1] : a[2]);
實施例:A = {1,3,5},B = {3,5,2}
s = (1-3)+(3-5)+(5-2) = -2-2+3 = -1
t = (1-3)*(1+3)+(3-5)*(3+5)+(5-2)*(5+2) = -8-16+21 = -3
t/s = 3
x = (-1 + 3)/2 = 1
y = (3 - (-1))/2 = 2
c[0] = 1
c[3] = 2
c[1] = 3
c[2] = 5
因此c根據需要獲取值{1,3,5,2}!
爲了好玩,這裏更緊湊的版本:
/* Declarations */
int a[3], b[3], c[4];
int s = 0, t = 0, k, i;
/* Actual algorithm */
for (i = 0; i < 3; i++) { s += (k = a[i]-b[i]); t += k * (a[i]+b[i]); }
t /= s;
c[0] = (s + t) >> 1;
c[3] = (t - s) >> 1;
c[1] = (a[0] == x ? a[1] : a[0]);
c[2] = (a[2] == x ? a[1] : a[2]);
需要注意的是冷靜不夠的,如果這個問題是廣義的,使N-1個元素是共享的,有兩個陣列中一個獨特的元素,這是一個O (n)算法,而基於交集和/或聯合的算法通常是O(n log n):)
作業問題? – Tim 2010-02-11 21:16:09
不是所有:),我正在尋找不規則網絡的三角剖分,如果每個點都有其周圍的兩個以上的三角形,我想測量角度... – 2010-02-11 21:18:39
即時通訊懶得寫LINQ加入,計數重複。 – 2010-02-11 21:19:02