题目描述:
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?
思路:
Java的异或(^)运算:两个操作数的位中,相同则结果为0,不同则结果为1。
一个数和0异或还是自己,一个数和自己异或是0。(0 ^ N = N, N ^ N = 0)
假定有2K+1个数,其中有2k个相同,需要找出不相同的那个数,可以利用异或运算符。
N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N
= (N1^N1) ^ (N2^N2) ^..............^ (Nx^Nx) ^ N
= 0 ^ 0 ^ ..........^ 0 ^ N
= N
class Solution {
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0)
return Integer.MIN_VALUE;
int res = nums[0];
for (int i = 1; i < nums.length; i++)
res ^= nums[i];
return res;
}
}