题目
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?
我的解法
之前就对该题了解过,所以知道采用XOR异或运算
异或运算法则:
参与运算的两个值,如果两个相应bit位相同,则结果为0,否则为1。即:
0^0 = 0,
1^0 = 1,
0^1 = 1,
1^1 = 0
按位异或的3个特点:
0^0=0,0^1=1
0 异或 任何数=任何数1^0=1,1^1=0
1异或任何数-任何数取反- 任何数异或自己=把自己置0
按位异或的几个常见用途:
- 使某些特定的位翻转
例如对数10100001的第2位和第3位翻转,则可以将该数与00000110进行按位异或运算。
10100001^00000110 = 10100111 - 实现两个值的交换,而不必使用临时变量。
例如交换两个整数a=10100001,b=00000110的值,可通过下列语句实现:
a = a^b; //a=10100111
b = b^a; //b=10100001
a = a^b; //a=00000110 - 在汇编语言中经常用于将变量置零:
xor a,a - 快速判断两个值是否相等
举例1: 判断两个整数a,b是否相等,则可通过下列语句实现:
return ((a ^ b) == 0)
我的代码:
public class Solution {
public int maxSubArray(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
result ^= nums[i];
}
return result;
}
}
采用Hash Table:
参考leetcode讨论区答案
public class Solution {
public int singleNumber(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();
Integer num, ans = 0;
for (int i = 0; i < nums.length; ++i) {
num = new Integer(nums[i]);
if (!set.add(num))
set.remove(num);
}
Iterator setIterator = set.iterator();
if (setIterator.hasNext()) {
ans = (Integer)setIterator.next();
}
return ans;
}
}