Problem 1001 Duplicate Pair

Problem 1001 Duplicate Pair

Accept: 5673    Submit: 27524
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.

 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=4,a={1,1,2,2},那么就应该输出1 2。思路是直接用桶排序,数组每个元素的值就是每个桶的下标 i,每个元素出现的次数就以该元素为下标的痛里面的值,若值大于等于2,输出。输出的时候要注意末尾没有空格!!!

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<cmath>
#include<algorithm> 
using namespace std;
int a[1000004];
int b[1000004];
int main()
{
    int n,num;
    int total;
    while(scanf("%d",&n)!=EOF)
    {
        memset(a,0,sizeof(a));//数组清零 
        total=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&num);
            a[num]++;//在对应值的桶里面个数加一 
            if(a[num]>=2)//桶里面元素个数超过或等于2个则输出
            { 
                total++;
                b[total]=num;       
            }   
        }
        for(int i=1;i<=total-1;i++)
            printf("%d ",b[i]); 
        printf("%d\n",b[total]);
    }
    return 0;
} 

以上是一位大佬帮我修改后的代码,不过又学到了一些东西
我一开始是不知道 memset(a,0,sizeof(a))这一句代码是什么意思
void *memset(void *s, int ch, size_t n);
函数解释:将s中前n个字节 (typedef unsigned int size_t)用 ch 替换并返回 s 。
memset:作用是在一段内存块中填充某个给定的值,它是对较大的结构体或数组进行清零操作的一种最快方法
memset是个函数,它在string.h头文件中有声明。
它有三个参数,一是所要set的首地址,二是set的值,三是set的字节数,
num肯定是个数组,因为数组在传参时能自动转成指向数组的首元素的指针,
如果不是数组,应该写成memset(&num, 0, sizeof(num));

点赞