[leetcode] Single Number II

Single Number II

 Total Accepted: 13814 Total Submissions: 42303My 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;
	}
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章