剑指offer——(3)数组中重复的数字

 
 

题目描述:

题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,
也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。例如,如果输入长度为7的数组{2, 3, 1, 0, 2, 5, 3},
那么对应的输出是重复的数字2或者3。
程序代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//面试题3(一):找出数组中重复的数字

bool cout_first(int *arr,int length)    //打印第一次出现的数字
{
	if (arr == NULL||length<=0)
	{
		return false;
	}
	for (int i = 0; i < length; i++)
	{
		if (arr[i]<0 || arr[i]>length)
		{
			return false;
		}
	}
	for (int i = 0; i < length; i++)
	{
		while (arr[i] != i)
		{
			int m = arr[i];
			int temp;
			if (arr[m] == arr[i])
			{
				printf("%d \n",arr[m]);
				return true;
			}
			temp = arr[m];
			arr[m] = arr[i];
			arr[i] = temp;
		}
	}
	return false;

}

int main()
{
	//int a[7] = {2,3,1,0,2,5,3};
	
	int i = 0, n = 1; //动态可变长数组的输入
	int *a;
	a = (int *)malloc(n*sizeof(int));
	do
	{
		scanf_s("%d",&a[i++],1);
		a=(int *)realloc(a, ++n*sizeof(int));
	} while (getchar() != '\n');
	for (i = 0; i < n - 1; i++)
	{
		printf("%d", a[i]);
	}
	printf("\n");
	
	cout_first(a, i);
}

猜你喜欢

转载自blog.csdn.net/lzmain/article/details/80260914
今日推荐