题目: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?
翻译:
一个数组中,除了一个数是唯一的,其他的数都存在2个,找出唯一的那个数.
要求:算法的时间复杂度为线性的,并且不用额外的内存空间
答案:
public class Solution {
public int singleNumber(int[] nums) {
int rst = nums[0];
int size = nums.length;
for (int i = 1; i < size; i++) {
rst = rst ^ nums[i];
}
return rst;
}
}
算法解释:
利用了^异或运算符的特性,任何两个相同数进行异或运算,结果都为0,0和任何数的异或运算都为那个数本身。由于当前数组中除了一个数是唯一的,其他的数都是成对存在的,因此,对所有的数进行异或运算之后的结果,就是那个唯一的数