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?
问题描述:给定一个整数数组,除了一个元素只出现一次外,其他每个元素都出现两次,找出这个只出现一次的数。
注:算法时间复杂度为线性的,不使用额外空间,即算法时间复杂度为O(n),空间复杂度为O(1)。
分析:使用异或运算,两个相同的数异或为0,不同的两个数异或为1,0与任何数异或为该任何数。
异或运算满足交换律、结合律,所以对于:a^b^c^d^b^a^c=(a^a)^(b^b)^(c^c)^d=d
所以对于该问题,将数组的所有整数做异或运算,最终的结果就是我们要找的只出现一次的数。
public class Solution {
public int singleNumber(int[] nums) {
int result = nums[0];
for(int i = 1;i < nums.length;i++){
result = result ^ nums[i];
}
return result;
}
}
拓展:一个数组存放若干整数,一个数出现奇数次,其余数均出现偶数次,找出这个出现奇数次的数?
该题的解题思路同样可以解决此问题,把所有整数做异或运算,最终的结果就是出现奇数次的数。