給出一個n + 2元素的數組。數組的所有元素都在1到n的範圍內。除了出現兩次的兩個數字外,所有元素都會出現一次。找到兩個重複的號碼。查找給定數組中的兩個重複元素
例如,陣列= {4,2,4,5,2,3,1}和n = 5
專家我知道這個問題4個可能解決方案,但最近,我遇到對此我的溶液無法解釋。下面是解決方案
traverse the list for i= 1st to n+2 elements
{
check for sign of A[abs(A[i])] ;
if positive then
make it negative by A[abs(A[i])]=-A[abs(A[i])];
else // i.e., A[abs(A[i])] is negative
this element (ith element of list) is a repetition
}
Example: A[] = {1,1,2,3,2}
i=1 ; A[abs(A[1])] i.e,A[1] is positive ; so make it negative ;
so list now is {-1,1,2,3,2}
i=2 ; A[abs(A[2])] i.e., A[1] is negative ; so A[i] i.e., A[2] is repetition,
now list is {-1,1,2,3,2}
i=3 ; list now becomes {-1,-1,2,3,2} and A[3] is not repeated
now list becomes {-1,-1,-2,3,2}
i=4 ;
and A[4]=3 is not repeated
i=5 ; we find A[abs(A[i])] = A[2] is negative so A[i]= 2 is a repetition,
This method modifies the original array.
的算法如何這個算法產生正確的結果,即它是如何working.Guys不要把這個作爲一個家庭作業的問題,因爲這問題已在最近被問微軟的採訪。
@leppie這是另一個問題,因爲有兩個重複的號碼 – 2011-02-01 07:37:05
@belisarius:對不起:) Upvoted to counter'close'vote。 – leppie 2011-02-01 07:38:43