LeetCode Review on Interview 2018 - LRI
Chapter 1 - 1
Given a non-empty array of integers, every element appears twice except for one. Finde that single one.
Note: your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
Method 1 :
using hashset to cut the search time.
java code:
public static int singleNumber(int[] nums){
if(nums.length==0) throw new IllegalArgumentException();
HashSet<Integer> set = new HashSet<>();
for(int i=0;i<nums.length;i++){
if(set.contains(nums[i])) set.remove(nums[i]);
else set.add(nums[i]);
}
if(set.size()>1) throw new IllegalArgumentException();
else{
Iterator<Integer> i = set.iterator();
return i.next();
}
}
Method 2:
XOR:
如果我们对 0 和二进制位做 XOR 运算,得到的仍然是这个二进制位
a⊕0=a
如果我们对相同的二进制位做 XOR 运算,返回的结果是 0
a⊕a=0
XOR 满足交换律和结合律
a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
所以我们只需要将所有的数进行 XOR 操作,得到那个唯一的数字。
java code:
public static int singleNumber(int[] nums){
int a = 0;
for(int i = 0;i<nums.length;i++){
a ^= nums[i]; // ^ is for xor
}
return a;
}