问题描述(难度简单-136)
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
1 | Input: [2,2,1] |
Example 2:
1 | Input: [4,1,2,1,2] |
XOR(异或)
如果a、b两个值不相同,则异或结果为1。如果a、b两个值相同,异或结果为0。
方法一:一边遍历Map
一遍遍历保留只出现一次的数字。
1 | public int singleNumber(int[] nums) { |
方法二:XOR
first , we have to know the bitwise XOR in java:
- 0 ^ N = N
- N ^ N = 0
So….. if N is the single number:
N1 ^ N1 ^ N2 ^ N2 ^…………..^ Nx ^ Nx ^ N= (N1^N1) ^ (N2^N2) ^…………..^ (Nx^Nx) ^ N= 0 ^ 0 ^ ……….^ 0 ^ N
= N
1 | public int singleNumber(int[] nums) { |
总结
采用XOR(异或)的方式,相同的数字都相互抵消了,最后留下单一的不同的数字。也就是方法二的精髓。