unique()函数是一个去重函数,STL中unique的函数 unique的功能是去除相邻的重复元素(只保留一个),还有一个容易忽视的特性是它并不真正把重复的元素删除。他是c++中的函数,所以头文件要加#include<iostream.h>,具体用法如下:
int num[100];
unique(num,mun+n)返回的是num去重后的尾地址,之所以说比不真正把重复的元素删除,其实是,该函数把重复的元素一到后面去了,然后依然保存到了原数组中,然后返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。
下面对一个数组中的元素进行去重示例:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
int main()
{
int a[120];
for(int i=0;i<5;i++)
scanf("%d",&a[i]);
int n=unique(a,a+5)-a;
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
除了用unique函数处理去重问题,也可以用转换数组下标的方法去除重复元素
举个例子:
Limak is a little polar bear. He has n balls, the i-th ball has size ti.
Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy:
- No two friends can get balls of the same size.
- No two friends can get balls of sizes that differ by more than 2.
For example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 (two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2).
Your task is to check whether Limak can choose three balls that satisfy conditions above.
The first line of the input contains one integer n (3 ≤ n ≤ 50) — the number of balls Limak has.
The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 1000) where ti denotes the size of the i-th ball.
Print "YES" (without quotes) if Limak can choose three balls of distinct sizes, such that any two of them differ by no more than 2. Otherwise, print "NO" (without quotes).
4 18 55 16 17
YES
6 40 41 43 44 44 44
NO
8 5 972 3 4 1 4 970 971
YES
In the first sample, there are 4 balls and Limak is able to choose three of them to satisfy the rules. He must must choose balls with sizes 18, 16 and 17.
In the second sample, there is no way to give gifts to three friends without breaking the rules.
In the third sample, there is even more than one way to choose balls:
- Choose balls with sizes 3, 4 and 5.
- Choose balls with sizes 972, 970, 971.
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int a[1000+50];
int b[1000+50];
int main(){
int t;
cin >> t;
memset(b,0,sizeof(b));
for(int i=0; i<t; i++){
cin >> a[i];
b[a[i]]++; //把输入的数字当成另一个数组的下标,数值变为非零
}
for(int i=0; i<1000+50; i++){
if(b[i]&&b[i+1]&&b[i+2]){
cout << "YES" << endl;
return 0;
}
}
cout << "NO" << endl;
return 0;
}