现在的位置: 首页 > 综合 > 正文

【面试题】数组中有两个元素出现了奇数次,其他元素出现了偶数次。找出这两个元素

2013年08月04日 ⁄ 综合 ⁄ 共 1691字 ⁄ 字号 评论关闭

数组中有两个元素出现了奇数次,其他元素出现了偶数次。找出这两个元素。

把原数组分为两个子数组。在每个子数组中,包含一个只出现一次的数字,而其他数字都出现两次。如果能够这样拆分原数组,按照前面的办法就是分别求出这两个只出现一次的数字了。

我们还是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。由于这两个数字肯定不一样,那么这个异或结果肯定不为0,也就是说在这个结果数字的二进制表示中至少就有一位为1。我们在结果数字中找到第一个为1的位的位置,记为第N位。现在我们以第N位是不是1为标准把原数组中的数字分成两个子数组,第一个子数组中每个数字的第N位都为1,而第二个子数组的每个数字的第N位都为0

现在我们已经把原数组分成了两个子数组,每个子数组都包含一个只出现一次的数字,而其他数字都出现了两次。因此到此为止,所有的问题我们都已经解决。

 

///////////////////////////////////////////////////////////////////////
//转载于 http://zhedahht.blog.163.com/blog/static/2541117420071128950682/
///////////////////////////////////////////////////////////////////////
//数组中有两个元素出现了奇数次,其他元素出现了偶数次。找出这两个元素
#include <stdio.h>
#include <stdlib.h>

bool IsBit1(int num, unsigned int indexBit)
{
      num = num >> indexBit;
      return (num & 1);
}

unsigned int FindFirstBitIs1(int num)
{
      int indexBit = 0;
      while (((num & 1) == 0) && (indexBit < 32))
      {
            num = num >> 1;
            ++ indexBit;
      }
      return indexBit;
}
void FindNumsAppearOnce(int data[], int length, int &num1, int &num2)
{
      if (length < 2)
	  {
		  return;
	  }
      // get num1 ^ num2
      int resultExclusiveOR = 0;
      for (int i = 0; i < length; ++ i)
	  {
		  resultExclusiveOR ^= data[i];
	  }
      // get index of the first bit, which is 1 in resultExclusiveOR
      unsigned int indexOf1 = FindFirstBitIs1(resultExclusiveOR); 
      num1 = num2 = 0;
      for (int j = 0; j < length; ++ j)
      {
            // divide the numbers in data into two groups,
            // the indexOf1 bit of numbers in the first group is 1,
            // while in the second group is 0
            if(IsBit1(data[j], indexOf1))
			{
				num1 ^= data[j];
			}
            else
			{
				num2 ^= data[j];
			}
      }
}


///////////////////////////////////////////////////////////////////////
// Is the indexBit bit of num 1?
///////////////////////////////////////////////////////////////////////

void main()
{
	int a[]={1,2,3,4,5,6,1,2,3,4,7,5,1,1,7,7};
	int n1 = -1;
	int n2 = -1;
	FindNumsAppearOnce(a,sizeof(a)/sizeof(a[0]),n1,n2);
	printf("%d,%d\n",n1,n2);
}

 

抱歉!评论已关闭.