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,0与该唯一数异或为数字本身
1.异或满足交换律。
2.相同两个数异或为0。
3.0异或一个数为那个数本身。
最后结果即出现1次的那个数。
class Solution {
public:
int singleNumber(int A[], int n) {
if(A == NULL || n <= 0)
return 0;
int num = 0;
for(int i = 0; i < n; ++i)
{
num ^= A[i];
}
return num;
}
};
博客围绕在整数数组中找只出现一次的数展开。已知除该数外其他数都出现两次,要求算法时间复杂度为O(n),空间复杂度为O(1)。利用异或运算特性,如交换律、相同数异或为0、0异或数为其本身,最终可找出该数。
1654

被折叠的 条评论
为什么被折叠?



