LeetCode137 Single Number II

question:

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?

 

方法參考他人博客,註釋自己標的.

 

int singleNumber(vector<int>& nums)
{
	int bitnum[32] = {0};
	int res = 0;
	for (int i = 0; i != 32; i++)	
	{
		for (int j = 0; j != nums.size(); j++)
		{
			bitnum[i] += (nums[j] >> i) & 1;    //統計32位中每一位1出現的次數
		}
		res += (bitnum[i] % 3) << i;  // 由於其他數字的某位(1或者0)都是X3重複出現,所以%3餘下的數字,肯定是"出現一次的數字"的第i位的數字,再通過移位換成十進制
	}
	return res;
}

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