137. 只出现一次的数字 II

题目链接: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;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值