一个非降序的数组,如果数组中有重复的数据,只保留一个,其余删除。
注: 如果数组是乱序的,可以现将数组进行非降序的排序(可以在C++中直接利用STL里的排序函数直接处理),这里只编写了非降序情况下的代码。
#include <stdio.h>
#include <stdlib.h>
int a[] = {1,2,2,3,4,5,5,5,6,7,8,8,9,10};
int ArrayRepDel(int [],int );
void show(int [],int );
int main()
{
int N = sizeof(a)/sizeof(int);
printf("Before the repeat delete:\n");
show(a,N);
int M = ArrayRepDel(a,N);
printf("The size of the new array M=%d\n",M);
printf("The new array:\n");
show(a,M);
return 0;
}
int ArrayRepDel(int a[],int n)
{
int i,j;
for(i = 0,j = 1;j < n;)
{
while(a[i] == a[j])
{
j++;
}
a[++i] = a[j];
j++;
}
return (i+1);
}
void show(int a[],int n)
{
int i;
for(i = 0;i < n;i++)
printf("%3d",a[i]);
printf("\n");
}