题目地址:
https://www.lintcode.com/problem/single-number/description
给定一个含 个数字的数组,其中有且仅有一个数字出现了 次,别的数都出现了 次。要求求出那个只出现了一次的数字。
可以利用异或 的运算性质来解题。注意到 ,并且异或满足交换律和结合律(详细证明见https://blog.csdn.net/qq_46105170/article/details/104082406),所以只需将数组中所有数字异或一遍即得到答案。代码如下:
public class Solution {
/**
* @param A: An integer array
* @return: An integer
*/
public int singleNumber(int[] A) {
// write your code here
int res = 0;
for (int i : A) {
res ^= i;
}
return res;
}
}
时间复杂度 ,空间 。