您的位置:首页 > 移动开发

Find the elements in the set that appears only once

2011-05-16 10:42 351 查看
given a set and each element in the set will appear twice. so how to find the elements that only appear once.

1. Use a bitmap and traverse the set. exclusive xor the value of bitmap at index with value of element in the set by 1. then if the element appears twice then the value will be zero and if the element appears only once then the value will be 1. trasverse
the bitmap then if the value is 1 at some index then the value represented by the index only appears once. pros. each to implement. cons. need a huge amount of space to store the bitmap.

2. Still use exclusive xor operation. we traverse the set and each time we meet a element we exclusive xor it to the final result. if the element appears twice then the element will have no influence on the final result because the result of that two same
element xor each other is zero. and the element that appears only once will have influence on the final result.

pros. only need one storage unit to store the final result. cons. only can find one element that appears once. if there are more than one element in the set that appears only once we cannot find them together.

3. In terms of invariant. the set is predefined then the sum of the set is fixed that we call it a invariant. if a element is missing in the set then the difference from the invariant is the missing element. the method still can only find the element in
the set where only one element appears once. if there are more than one element in the set that appears only once we cannot find them. if we need find them then we need more information. we can use multiplication of the element in the set as another invariant.
and quotient of dividing invariant by muplication of the element in the set is the multiplication value of two missing element in the set. now we have two equation and two variants: x+y=a,xy=b then we can acquire a and b.

Summary

The problem can be abstracted as the problem: given a set and element in the set is within the predefined range. so now we know there is one or two elements missing in the set then how to find them.

1. xor is very useful operation. because if two elements with same value xor each other the result is zero. and if an element xor zero the result is itself. it is very useful to test whether two element are equal.

2. invariant is also very useful. a predefined set is a invariant. the missing element is the difference from the invariant, through which we can find the missing elements.

Above methods are extracted from chapter 1.5 in "beauty of programming"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐