问题:
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?
给你一个整数数组,其中只有一个元素出现一次,其他元素都出现两次,找到那个出现一次的数。
思路一:不考虑附加条件,可以采用暴力的方法,依次对每个整数都进行比较
思路二:如果两个数相同,则两个数进行异或为零。对所有的数都进行异或,则结果就是那个单一数。
class Solution {
public int singleNumber(int[] nums) {
for(int i = 1;i<nums.length;i++){
nums[0]^=nums[i];//异或
}
return nums[0];
}
}