[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;
	}
};



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