Problem 1001 Duplicate Pair
Accept: 5021 Submit: 23768
Time Limit: 1000 mSec Memory Limit : 65536 KB
Problem Description
An array of length n, with address from 1 to n inclusive, contains entries from the set {1,2,...,n-1} and there's exactly two elements with the same value. Your task is to find out the value.
Input
Input contains several cases.
Each case includes a number n (1<n<=10^6), which is followed by n integers.
The input is ended up with the end of file.
Each case includes a number n (1<n<=10^6), which is followed by n integers.
The input is ended up with the end of file.
Output
Your must output the value for each case, one per line.
Sample Input
2
1 1
4
1 2 3 2
Sample Output
1
2
题目大意:输入N数,这N数的范围在1~n-1,其中有两个数是相同的,找出这个数?
解题思路:N的范围是1~10^6;故用数组存下n个数,再找的话太费时;
因为N个数的范围是1~n-1;所以可以开一个数组a[1000010];数组的下标i表示这1~n-1这些数;数组的值a[i]用来表示数 i出现的次数。
当a[i]>1,那么,i就是所要找的数。
AC代码:
#include<stdio.h>
#include<string.h>
int a[1000010];
int main()
{
int n,i,j,m;
while(scanf("%d",&n)!=EOF)
{
memset(a,0,sizeof(a));
for(i=1;i<=n;i++)
{
scanf("%d",&j);
a[j]++;
if(a[j]>1)
m=j;
}
printf("%d\n",m);
}
return 0;
}