[LeetCode] Single Number III

本文介绍如何利用哈希表解决特定问题,并探讨如何在常数时间和空间下实现这一目标。通过分析位运算和位操作,我们能够找到并解决特定数值问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This problem can also be solved using Hash map and this idea is quite simple on implementation.


But how to do it in linear time and constant space? 


First of all, we know that if we do XOR to all the elements, we can get a^b in which a,b are the numbers we want respectively. Now, need to analysis the result of a^b. If any bit is '1' means a and b are different on this bit. So, we can find this one bit and '&' with all other numbers to get those have the same bit and XOR them. Then we get the number, say a. a^b^a = b. Done.


vector<int> singleNumber(vector<int>& nums) {
	int len=nums.size(); 
	vector<int> res;
	if(len<2) return res;
	int first = 0;
	for(int i=0;i<len;i++)
	{
		first=first^nums[i];
	}
	int diff = 1;
	while((first&diff)!=diff)
	{
		diff=diff<<1;
	}
	int result=0;
	for(int i=0;i<len;i++)
	{
		if((nums[i]&diff)==diff)
		{
			result=result^nums[i];
		}
	}
	res.push_back(result);
	res.push_back(first^result);
 	return res;
}
Two things are tricky here: the priority of '&' is somehow lower than != and ==, and diff<<1 won't change diff.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值