由于是整数数组。阵列中的每个编号重复的次数为奇数,但是只有1号被重复的偶数次。找到这个数字。
Given is an array of integers. Each number in the array repeats an ODD number of times, but only 1 number is repeated for an EVEN number of times. Find that number.
我在想一个哈希表,每个元素的数量。它需要O(n)的空间。有没有更好的办法?
I was thinking a hash map, with each element's count. It requires O(n) space. Is there a better way?
哈希地图是好的,但你需要存储的每个元素的数模2。 所有这些都将最终被1(奇)除0(偶数)-count元素。
Hash-map is fine, but all you need to store is each element's count modulo 2. All of those will end up being 1 (odd) except for the 0 (even) -count element.
(如阿莱克斯摹说,你并不需要使用运算(数+%2
),只有XOR(计数^ =为0x1
);但任何编译器将优化反正)
(As Aleks G says you don't need to use arithmetic (count++ %2
), only xor (count ^= 0x1
); although any compiler will optimize that anyway.)