Single Number
Total Accepted: 62249 Total Submissions: 137347
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?
這個題是LeetCode上面AC率最高的一道題。題目是給定一個序列,所有的數字都出現兩次,只有一個數字出現一次,找出來這個數字。
我一開始使用了map儲存數字和出現頻率,然後遍歷map找到value爲1的輸出key。
class Solution {
public:
int singleNumber(int A[], int n) {
map<int, int> mp;
for(int i = 0; i < n; ++i)
{
mp[A[i]]++;
}
for(map<int, int>::iterator it = mp.begin(); it != mp.end(); ++it)
{
if(it->second == 1)
return it->first;
}
}
};
但是這個方法時間複雜度是很高的map的實現是紅黑樹,插入/查找元素的時間複雜度是O(logN),所以這個算法的時間複雜度應該是O(NLogN)並不是Note裏面的O(N),使用的額外空間也非常多。看到Discuss裏面其他人的解法基本上都是使用位運算,利用a ^ a == 0這個特性將所有元素全部異或一遍,剩餘的結果就是那個出現次數一的元素。
class Solution {
public:
int singleNumber(int A[], int n) {
int result = 0;
for(int i = 0; i < n; ++i)
result ^= A[i];
return result;
}
};