题目链接:leetcode.
哈希表,O(n),O(n)
/*
执行用时:12 ms, 在所有 C++ 提交中击败了35.80%的用户
内存消耗:9.9 MB, 在所有 C++ 提交中击败了5.13%的用户
*/
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int, int> M;
for(auto x : nums)
{
M[x]++;
}
for(auto m : M)
{
if(m.second == 1)
return m.first;
}
return 0;
}
};
计数,按位遍历,对3取余,时间复杂度O(32n) 空间复杂度O(1)
/*
执行用时:12 ms, 在所有 C++ 提交中击败了35.80%的用户
内存消耗:9.3 MB, 在所有 C++ 提交中击败了38.49%的用户
*/
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for(int i = 0;i < 32;++i)
{
int cnt = 0;
for(auto x : nums)
{
if((x >> i) & 1)
{
cnt++;
}
}
if(cnt % 3)
ans |= (1 << i);
}
return ans;
}
};
真值表,用a,b表示每一位的状态,00、01、10循环
O(n) O(1)
/*
执行用时:8 ms, 在所有 C++ 提交中击败了74.16%的用户
内存消耗:9.2 MB, 在所有 C++ 提交中击败了78.17%的用户
*/
class Solution {
public:
int singleNumber(vector<int>& nums) {
int a = 0, b = 0;
for(auto x : nums)
{
int t = (a ^ b) & (a ^ x);
b = (~a) & (b ^ x);
a = t;
}
return b;
}
};
还可以用新的b来推a,省去临时变量t (但新a推不出b,画个真值表就知道了
/*
执行用时:8 ms, 在所有 C++ 提交中击败了74.16%的用户
内存消耗:9.2 MB, 在所有 C++ 提交中击败了94.30%的用户
*/
class Solution {
public:
int singleNumber(vector<int>& nums) {
int a = 0, b = 0;
for(auto x : nums)
{
b = (~a) & (b ^ x);
a = (~b) & (a ^ x);
}
return b;
}
};

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



