剑指Offer----面试题40:数组中出现一次的数字

本文介绍了一种高效算法,用于从整型数组中找出仅出现一次的两个数字,要求时间复杂度为O(n),空间复杂度为O(1)。通过位操作实现算法逻辑,并通过实例验证了算法的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:


一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度为O(n),空间复杂度为O(1)。


分析


例如输入数组{2,4,3,6,3,2,5,5},因为只有4、6这两个数字出现一次,其他数字出现了两次,所以输出4、6。




源码

#include<iostream>

using namespace std;

unsigned int FindFirstBitIs1(int num)
{
	unsigned int index = 0;
	while ((num & 0x1) == 0 && index <= 8 * sizeof(int))
	{
		num >>= 1;
		++index;
	}

	return index;
}

bool IsBit1(int num, int index)
{
	num >>= index;
	if ((num & 0x1) == 1)
		return true;
	else
		return false;
}

void FindNumbersAppearOnce(int *arr, int length, int &numA, int &numB)
{
	if (arr == nullptr || length <= 1)
		return;
	
	int resultOr = 0;
	for (int i = 0; i < length; ++i)
		resultOr ^= arr[i];

	unsigned int indexOf1 = FindFirstBitIs1(resultOr);

	numA = numB = 0;

	for (int i = 0; i < length; ++i)
	{
		if (IsBit1(arr[i], indexOf1))
			numA ^= arr[i];
		else
			numB ^= arr[i];
	}
}

void test1()
{
	cout << "=================test1:nullptr===============" << endl;
	int numA = 0;
	int numB = 0;
	int *arr = nullptr;
	FindNumbersAppearOnce(arr, 0, numA, numB);
	if (numA == 0 && numB == 0)
		cout << "没有找到" << endl;
	else
		cout << "找到了,numA = " << numA << "\tnumB = " << numB << endl;
}

void test2()
{
	cout << "=================test1:{2,4,3,6,3,2,5,5}===============" << endl;
	int numA = 0;
	int numB = 0;
	int arr[] = { 2, 4, 3, 6, 3, 2, 5, 5 };
	FindNumbersAppearOnce(arr, sizeof(arr)/sizeof(int), numA, numB);
	if (numA == 0 && numB == 0)
		cout << "没有找到" << endl;
	else
		cout << "找到了,numA = " << numA << "\tnumB = " << numB << endl;
}

void test3()
{
	//其他的数字出现次数智能是偶数次,否则结果不正确
	cout << "=================test1:{4,6,1,1,1,1,1, 1}===============" << endl;
	int numA = 0;
	int numB = 0;
	int arr[] = { 4, 6, 1, 1, 1, 1, 1, 1 };
	FindNumbersAppearOnce(arr, sizeof(arr) / sizeof(int), numA, numB);
	if (numA == 0 && numB == 0)
		cout << "没有找到" << endl;
	else
		cout << "找到了,numA = " << numA << "\tnumB = " << numB << endl;
}

int main()
{
	test1();
	cout << endl;
	test2();
	cout << endl;
	test3();
	cout << endl;

	system("pause");
	return 0;
}

运行结果:
=================test1:nullptr===============
没有找到

=================test1:{2,4,3,6,3,2,5,5}===============
找到了,numA = 6 numB = 4

=================test1:{4,6,1,1,1,1,1, 1}===============
找到了,numA = 6 numB = 4

请按任意键继续. . .




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值