[leetcode] Single Number II

Single Number II

  Total Accepted: 13814  Total Submissions: 42303 My Submissions

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Have you been asked this question in an interview? 


举个例子说明:




如上图所示,用ones记录,出现所有int, 响应的位1出现的次数 (mod 3) 等于1
tows记录, 响应的位1出现的次数(mod 3)等于2



class Solution {
public:
	int singleNumber(int A[], int n)
	{
		//本程序可以用下面的例子说明:
		//输入A[4] = {3, 3, 3, 1};
		/*
			初始化:one = 0; tows = 0; xthrees = 0;
			开始循环 i = 0
			tows = tows | (ones & 3) = 0 | (0 & 3) = 0;
			ones = ones ^ 3 = 0 ^ 0x0000 0011 = 0x0000 0011 = 3;
			后面三行代码将ones和tows中的同时出现的1去掉
			ones = 3; tows = 0;
			第二遍循环i=1
			tows = tows | (3 & 3) = 0 | (3) = 3;
			ones = ones ^ 3 = 0;
			去掉共同的1, ones = 0, tows = 3;
			第三遍循环i=2
			tows = tows | (0 & 3) = 3;
			ones = ones ^ 3 = 3;
			去掉共同的1,ones = 0, tows = 0;
			第四遍循环i=3
			tows = tows | (ones & 1) = 0;
			ones = ones ^ 1 = 1;
			去掉共同的1 ones = 1, tows = 0;
			最终的结果是ones = 1就是只出现一次的那个数
		*/
		//用ones记录到当前计算的变量为止,二进制1出现“1次”(mod 3 之后的 1)的数位。
		//	举个例子
		int ones = 0, twos = 0, xthrees = 0;
		for (int i = 0; i < n; ++i)
		{
			twos |= (ones & A[i]);
			ones ^= A[i];//异或操作

			//下面三行代码的作用是:
			//	将ones和twos中相同位置“都出现”的1设置为0,举例说明:
			//	ones = 0x0010, tows = 0x0011
			//	xthrees = ~(ones&0x11) = ~(0x0010) = 0x1101
			//	ones = one & xthrees = 0x0010 & 0x1101 = 0x0000;
			//	twos = twos & xthrees = 0x0011 & 0x1101 = 0x0001

			//为啥将ones tows中的相同位置中都出现的1设置为0,是为了
			//	ones和tows都出现,说明,一个数出现了三次,就去掉
			xthrees = ~(ones & twos);
			ones &= xthrees;
			twos &= xthrees;
		}

		return ones;
	}
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值