指定された要素に加えて、整数の非空の配列は、一度だけ表示され、各要素の残りの部分は二回表示されます。要素のみに一度表示されていることを知るために。
説明:
あなたのアルゴリズムは線形時間複雑性を持っている必要があります。あなたはそれを達成するために余分なスペースを使用することはできませんか?
例1:
入力:[2,2,1]
出力:1
例2:
入力:[4,1,2,1,2]
出力:4
方法1:ハッシュテーブル
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int singleNumber(vector<int>& nums) {
for(int i=0;i<nums.size();i++){
if(m_map.count(nums[i])==0){
m_map[nums[i]]++;
}else{
m_map[nums[i]]--;
}
}
int res;
unordered_map<int,int>::iterator it = m_map.begin();
while(it!=m_map.end()){
if(it->second==1){
res = it->first;
break;
}
it++;
}
return res;
}
private:
unordered_map<int,int> m_map;
};
int main(){
vector<int> test ={4,1,2,1,2};
Solution *ps = new Solution();
cout<<ps->singleNumber(test)<<endl;
return 0;
}
方法2:ビット
ビット操作:
1。可換:A ^ B ^ A ^ C ^ C <=> B
任意の数の、又は異なる任意の数2. 0 N- ^ = 0> N-
3 XOR 0の同じ数:N ^ N => 0
例えば:
VAR A = [2,3,2,4,4]
2 ^ 2 ^ 3 ^ 4 ^ 4 ^ 2に相当する2 ^ 4 ^ 4 ^ 3 => 0 ^ 0 ^ 3 => 3
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int singleNumber(vector<int>& nums) {
int cur = 0;
for(int i=0;i<nums.size();i++){
cur = cur^nums[i];
}
return cur;
}
};
int main(){
vector<int> test ={4,1,2,1,2};
Solution *ps = new Solution();
cout<<ps->singleNumber(test)<<endl;
return 0;
}