问题
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:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
思路
常规解法
两层循环,时间复杂度为o(n2)
空间复杂度为 o(n)
public int findSingle_1(int[] nums) {
if (nums.length < 2) {
return nums[0];
}
Set<Integer> hashSet = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
boolean isSingle = true;
if(hashSet.contains(nums[i])) {
continue;
}
hashSet.add(nums[i]);
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
isSingle = false;
break;
}
}
if (isSingle) {
return nums[i];
}
}
throw new IllegalArgumentException("not found");
}
基于比特操作的解法
原理:相同值的异或结果为0
时间复杂度 o(n),空间复杂度o(1)
public int findSingle_2(int[] nums) {
int res = 0;
for(int num : nums) {
res ^= num;
}
return res;
}
知识点
比特位操作
逻辑操作
a & b 与操作,有一个为0,则为0,否则为1
a | b 或操作,有一个为1,则为1,否则为0
a ^ b 异或操作,相同则为1,否则为0;若2个数相同,则异或操作后得到0;0 ^ a = a 任何值异或,得到自身;两个不相等的值异或,不可能得到0;
~ b 取反操作;
移位操作
<< 左移 等价于x2
‘>>’ 右移 等价于 /2