《剑指offer》-数组中只出现一次的数字


/*
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

思路:
如果是只有一个数字出现一次,那么所有数字做异或就得到结果;
现在有两个数字x,y分别出现一次,其他数字出现两次,那么所有数字异或的结果是result = x^y
x^y肯定不等于0,那么找其二进制表示中不等于0的一个位,比如从右到左第一个位置好了,那么用这个位置能区分开来这两个数字,以及其他的数字,每两个一样的数字都处于同一边。
*/
class Solution {
public:
	void FindNumsAppearOnce(vector<int> data, int* num1, int *num2) {
		int res = data[0];
		for (int i = 1; i < data.size(); i++){
			res = res ^ data[i];
		}
		int cnt = 0;
		while (res % 2 != 1){
			res = res >> 1;
			cnt = cnt + 1;
		}
		*num1 = *num2 = 0;
		for (int i = 0; i < data.size(); i++){
			if ((data[i] >> cnt) & 1){
				*num1 ^= data[i];
			}
			else{
				*num2 ^= data[i];
			}
		}
	}
};

原文地址:https://www.cnblogs.com/zjutzz/p/6618962.html