如何去掉数组里重复的数据
如:有一数组 a[]={5,2,2,7,2};
进行筛选后的数组 就变为{5,2,7}
求思路,。.
[解决办法]
- C/C++ code
#include <set>#include<iostream>using namespace std;int main(){ int a[6] = {1,2,3,1,2,5}; set<int>iSet; int i = 0; set<int>::iterator setIt; for (i=0;i<6;i++) { iSet.insert(a[i]); } setIt = iSet.begin(); while (setIt != iSet.end()) { cout << *setIt << " "; ++setIt; } cout << endl; return 0;}
[解决办法]
[解决办法]
- C/C++ code
while (setIt != iSet.end()) { a[i++] = *setIt; cout << *setIt << " "; ++setIt; }
[解决办法]
[解决办法]
你可以自定义一个数据Buffer,每次从要筛选数组中遍历一个数时,将该数与Buffer中的数比较,如果等于就筛除,Buffer中的数做到由小到大排列。
[解决办法]
定义一个辅助数组b,a数组的值为b数组下标,扫描a数组,令b[a[i]]=1; 扫描b数组,当b[i]=1时输出i
如果a数组值的集合不确定,扫描a数组,构造一颗二叉树,最后输出二叉树。
[解决办法]
c语言版的
int aa(int a[], int n)
{
int *b=a;
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(b[i]==b[j])
{
a[j]=a[n-1];
n--;
j--;
}
}
}
for(i=0;i<n;i++)
{
a[i]=b[i];
}
return n;
}
[解决办法]
C版本的差不多,先排序,再去重复
- C/C++ code
#include "stdio.h"#include "stdlib.h"#include "string.h"int compare(const void *p1, const void *p2){ return (*(char*)p1 - *(char*)p2);}void show_bytes(const char* p, int len){ int i; for(i=0;i<len;i++){ printf("%02X, ", p[i]); if( (i&15) == 15)printf("\n"); }}int unique(char* p, int len){ int i; int j = 0; qsort(p,len,1,compare); for(i=0;i<len;i++){ if(p[i] != p[j]){ p[++j] = p[i]; } } return j+1;}int main(){ char arr[] = {1,2,5,3,4,7,4,8,5,3,5,4,3,6,7,7}; int len = unique(arr, sizeof(arr)); show_bytes(arr, len); return 0;}
[解决办法]
如果你只要输出去掉 重复, 可以不需要排序
[解决办法]
int aa(int a[], int n)
{
int *b=a;
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(b[i]==b[j])
{
while(1)
{
int m = j;
a[m]=a[m+1];
m++;
if (m == n-1)
break;
}
n--;
}
}
}
for(i=0;i<n;i++)
{
cout<<a[i]<<",";
}