01 Find the odd int(找到出现次数为奇数的int)
2016-11-18 15:59
183 查看
Description:
Given an array, find the int that appears an odd number of times.There will always be only one integer that appears an odd number of times.
public class FindOdd { public static int findIt(int[] A) { return xor; } }
解法一
一般的解法,笨拙的方法,使用Map的性质,先遍历每一个元素,将元素作为key,value为它出现的次数,然后再使用Entry的方式遍历,求得value为奇数的entry的key,这个key就是需要的值解法二
巧解(我还需要继续学习提升自己的姿势水平).方法利用了异或的性质(相同的数字异或结果为0, a ⊕b ⊕ c = a ⊕ (b ⊕ c) = (a ⊕ b) ⊕ c;).所以将集合中所有中数字进行异或就可以了,所有的成对的元素异或的结果为0,只剩下最后一个出现次数为奇数的元素.代码如下:
public class FindOdd { public static int findIt(int[] A) { int xor = 0; for (int i = 0; i < A.length; i++) { xor ^= A[i]; } return xor; } }
相关文章推荐
- (HDUSTEP 2) hdu 2095 find your present (2)(找到出现奇数次的那个数)
- (使用STL自带的排序函数进行排序7.3.6)POJ 2945 Find the Clones拷贝相同次数的文本出现了多少次()
- 现在有N个数字,其中只有一个数字出现的次数是奇数次,如何找到这个数字?
- could not find the main class win7/xp 双击执行jar包出现:could not find the main class
- VS2010 C++ Debug 出现错误“Cannot find or open the PDB file”(续)
- How to: Find the fastest apt mirror server for Debian or Ubuntu(如何为ubuntu或debian找到最快的apt镜像站点)
- 当启动文档转换负载平衡器服务时出现如下问题The system cannot find the file specified的解决方案
- Eclipse中执行Ant脚本出现Could not find the main class的问题及解
- c++执行程序出现"unable to find a version of the runtime"的错误提示
- 问题解决:打开word2010时出现“Cannot find the Word template:WordToRqm.dot”
- VS2010 C++ Debug 出现错误“Cannot find or open the PDB file”
- struts2文件下载出现Can not find a java.io.InputStream with the name的错误
- How to find out the odd charactor?
- struts2文件下载出现Can not find a java.io.InputStream with the name的错误
- myeclipse启动tomcat 出现could not find the main class Program will exit
- 安装VisualDSP++出现Install cannot proceed.Could not find XML file or the XML file may be corrupted!
- 今天打开Vs2005 出现 Could not find the Visual SourceSafe Internet Web Service connection...
- vs .net 2005 打开VSS项目时出现:"could not find the visual sourcesafe internet web service connection"的解决方案
- .net中创建目录的问题(未找到路径X的一部分|Could not find a part of the path)
- struts2文件下载出现Can not find a java.io.InputStream with the name的错误