Leetcode Single Number
Given an 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?
解题思路:
1. 瞬间想到用HashSet, 但是时间复杂度也是可想而知。
2. 参考答案发现巧妙的方法,使用异或(XOR)^ 速度超快!!!
we use bitwise XOR to solve this problem :
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
Java code:
方法一: HashSet(不推荐,速度慢)
public int singleNumber(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i< nums.length; i++){ if(set.contains(nums[i])){ set.remove(nums[i]); }else{ set.add(nums[i]); } } Iterator it = set.iterator(); int result = (int)it.next(); return result; }
方法二:
public int singleNumber(int[] nums) { int result = 0; for(int i = 0; i < nums.length; i++){ result ^= nums[i]; } return result; }
Reference:
1. https://leetcode.com/discuss/53327/easy-java-solution-tell-you-why-using-bitwise-xor