首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

查找数组中重复的数字解决办法

2012-04-27 
查找数组中重复的数字n array of length n, with address from 1 to n inclusive, contains entries from

查找数组中重复的数字
n 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.

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

下面是我写的,一直超时,请问怎么改

C/C++ code
#include<stdio.h>int main(){    int n,i,j,temp;    while(scanf("%d",&n)==1)    {        int a[n];        for(i=0;i<n;i++)            scanf("%d",&a[i]);        while(getchar()!='\n')            continue;        for(i=n-1;i>0;i--)            for(j=0;j<n-1;j++)                if(a[j]<a[j+1])                {                    temp=a[j];                    a[j]=a[j+1];                    a[j+1]=temp;                }        for(i=0;i<n-1;i++)            if(a[i]==a[i+1])            {                printf("%d",a[i]);                break;            }        putchar('\n');    }    return 0;}


[解决办法]
State Language Time Mem Len
Accepted GNU C++ 296 ms 208KB 308B

C/C++ code
#include <stdio.h>int main(void){    int n   = 0;    int val = 0;    int sum = 0;    while(EOF != scanf("%d%*c", &n))    {        if(0 == n) break;        for(sum = 0; n > 0; n --)        {            scanf("%d", &val);            sum += val;            sum -= (n - 1);        }        printf("%d\n", sum);  }  return 0;} 

热点排行