There is an array of 1001 elements, the elements are all integers from 1 to 1000, and only one element is repeated. Find out the repeated elements

Method 1: Apply for a new array to record the number of occurrences of each element, and then scan the new array

Method Two:

First remove one of the repeated elements, leaving only 1,000 non-repetitive elements.

Then the 1000 numbers must be: 1, 2, 3,..., 1000.

The sum of 1000 elements is S, S=1+2+...+1000.

Assuming that the sum result of the original 1001 elements is T, the repeated element a=TS.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 1001

int main()
{
	srand(time(NULL));
	int arr[MAX];

	//以下都是在生成1001个元素的数组,不用管
	for (int i = 0; i < 1000; ++i)
	{
		arr[i] = i + 1;
	}
	for (int i = 0; i < 1000; ++i)
	{
		int j = rand() % (i + 1);
		int tmp = arr[j];
		arr[j] = arr[i];
		arr[i] = tmp;
	}
	arr[1000] = rand() % 1001;//设定arr[1000]是重复元素
	printf("%d\n" , arr[1000]);

	int S=0 , T=0 , a;
	for (int i = 0; i < 1000; i++)
	{
		S += i + 1;
		T += arr[i];
	}
	T += arr[1000];
	a = T - S;
	printf("重复数是:%d\n" , a);
	return 0;
}

 

 

 

Guess you like

Origin blog.csdn.net/qq_43496435/article/details/113805267