数组-----不修改数组找出重复的数字

不修改数组找出重复的数字
题目:在一个长度为n+1的数组里的所有数字都在1到n的范围内,所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的 数组。例如,如果输入长度为8的数组{2, 3, 5, 4, 3, 2, 6, 7},那么对应的输出是重复的数字2或者3。

方法:我们把从1~n的数字从中间的数字m分为两部分,前面一半为1~m,后面一半为m+1~n,如果1~m的数字数目超过m,则这一半的区间一定有重复包含的数字;否则另一半有重复数字;那么我们可以继续把包含重复数字的区间一分为二,直到找到这个重复数字为止,方法与二分查找法类似,但是多了一步统计区间数字的数目,时间复杂度O(nlogn),空间复杂度O(1).

//不修改数组找出重复的数字
// 题目:在一个长度为n+1的数组里的所有数字都在1到n的范围内,所以数组中至
// 少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的
// 数组。例如,如果输入长度为8的数组{2, 3, 5, 4, 3, 2, 6, 7},那么对应的
// 输出是重复的数字2或者3。
#include <cstdio>

int CountRange(const int *arr, int length, int start, int middle);

int GetDuplication(const int* arr, int length)
{
	if (arr == nullptr || length <= 0)
		return 0;
	int start = 1;
	int end = length - 1;
	while (end >= start)
	{
		int middle = ((end - start) >> 1) + start;
		int count = CountRange(arr, length, start, middle);
		if (start == end)
		{
			if (count > 1)
				return start;
			else
				break;
		}
		if (count > (middle - start + 1))
			end = middle;
		else
			start = middle + 1;
	}
	return 0;
}

int CountRange(const int *arr, int length, int start, int middle)
{
	if (arr == nullptr)
		return 0;
	int count = 0;
	for (int i = 0;i < length;++i)
		if (arr[i] >= start && arr[i] <= middle)
			++count;
	return count;
}

void Test1()
{
	int array1[] = { 0,1,2,3,3,4 };
	int Duplication = GetDuplication(array1, sizeof(array1) / sizeof(array1[0]));
	if (Duplication)
		printf("数字:%d 重复", Duplication);
	else
		printf("没有数字重复");
	printf("\n");
}

void Test2()
{
	int array2[] = { 0,1,2,3,4,5 };
	bool Duplication = GetDuplication(array2, sizeof(array2) / sizeof(array2[0]));
	if (Duplication)
		printf("数字:%d 重复", Duplication);
	else
		printf("没有数字重复");
	printf("\n");
}

void Test3()
{
	int array3[] = { 0,1,1,2,2,3 };
	bool Duplication = GetDuplication(array3, sizeof(array3) / sizeof(array3[0]));
	if (Duplication)
		printf("数字:%d 重复", Duplication);
	else
		printf("没有数字重复");
	printf("\n");
}

void Test4()
{
	int array4[] = { 0,1,2,3,4,6 };
	int Duplication = GetDuplication(array4, sizeof(array4) / sizeof(array4[0]));
	if (Duplication)
		printf("数字:%d 重复", Duplication);
	else
		printf("没有数字重复");
	printf("\n");
}

void Test5()
{
	int array5[] = { -1};
	int Duplication = GetDuplication(array5, sizeof(array5) / sizeof(array5[0]));
	if (Duplication)
		printf("数字:%d 重复", Duplication);
	else
		printf("没有数字重复");
	printf("\n");
}

int main()
{
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39916039/article/details/82080867