LintCode-落单的数 III

给出2*n + 2个的数字。除当中两个数字之外其它每一个数字均出现两次,找到这两个数字。

您在真实的面试中是否遇到过这个题? 
Yes
例子

给出 [1,2,2,3,4,4,5,3]。返回 1和5

挑战

O(n)时间复杂度,O(1)的额外空间复杂度

标签 Expand  

相关题目 Expand 


分析:这样的抖灵巧的题要是面试官面我,我肯定会批判一番的!把全部数亦或下,得到的数能够求出两不同数的亦或值,这样能够找到一个位,在该位上能够把全部数分成两部分。没部分能够套用之前的“全部数都出现两次,除了当中一个数”的代码。

代码:

class Solution {
public:
	/**
	* @param A : An integer array
	* @return : Two integers
	*/
	vector<int> singleNumberIII(vector<int> &A) {
		// write your code here
		int k = findFirstDiffBit(A);
		int ret1 = findOne(A, k, true);
		int ret2 = findOne(A, k, false);
		vector<int> ret;
		ret.push_back(ret1);
		ret.push_back(ret2);
		return ret;

	}
	int findFirstDiffBit(vector<int>& A)
	{
		int x = 0;
		for (auto i : A)
			x ^= i;
		for (int i = 0;i<32;i++)
		{
			if ((1 << i)&x)
				return i;
		}
	}
	int findOne(vector<int>&A, int k, bool first)
	{
		int ret = 0;
		for (auto x : A)
		{
			if (first)
			{
				if ((1 << k)&x)
					ret ^= x;
			}
			else
			{
				if (((x>>k)&1) == 0)
					ret ^= x;
			}
		}
		return ret;
	}
};


原文地址:https://www.cnblogs.com/zsychanpin/p/7308470.html