题目
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?
解答
思路:异或定义:相异为真,相同为假。相同数字异或为0,最后剩下的就是只出现过一次的。
class Solution {
public int singleNumber(int[] nums) {
int i = 1, result = nums[0];
while (i < nums.length) result ^= nums[i++];
return result;
}
}