寻找一个数字,重复甚至没有的时候,所有的其他号码重复的次数多无 [英] Finding a number that repeats even no of times where all the other numbers repeat odd no of times

查看:107
本文介绍了寻找一个数字,重复甚至没有的时候,所有的其他号码重复的次数多无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于是整数数组。阵列中的每个编号重复的次数为奇数,但是只有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.)

这篇关于寻找一个数字,重复甚至没有的时候,所有的其他号码重复的次数多无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆