题目
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 itwithout using extra memory?
//空间O(n), 时间O(nlogn)
class Solution {
public:
int singleNumber(int A[], int n) {
set<int> se;
for (int i = 0; i < n; ++i) {
auto it = se.find(A[i]);
if (it == se.end()) {
se.insert(A[i]);
} else {
se.erase(it);
}
}
auto it = se.begin();
return *it;
}
};
// 时间O(nlogn),空间in-place
class Solution {
public:
int singleNumber(int A[], int n) {
sort(A, A+n);
for (int i = 0; i < n ; i = i+2) {
if (A[i] != A[i+1]) {
return A[i];
}
}
}
};
异或
异或运算符: ^
同为0,异为1.
同为0,异为1.
10
^ 00
-----
10
^ 00
-----
10
// 0与任何数字a异或,结果为a
10
^ 10
-----
00
^ 10
-----
00
// 数字a与数字a异或结果为0
// 从以上两个结论推导:a^b^b = a
class Solution
{
public:
int singleNumber(int A[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
while (--n!=0) A[n-1]^=A[n];
return A[0];
}
};
public:
int singleNumber(int A[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
while (--n!=0) A[n-1]^=A[n];
return A[0];
}
};