问题
If I have an array set up as:
test[10] = {1,2,1,3,4,5,6,7,8,3,2}
I want to return the number 3 since there is a duplicate 1, a duplicate 2 and a duplicate 3. How can I achieve this? Efficiency doesn't matter.
回答1:
First you must sort the array so it is easier to find duplicates.
Here is an example of a sort (bubble sort):
void bubbleSort(int numbers[], int array_size) {
int i, j, temp;
for (i = (array_size - 1); i > 0; i--) {
for (j = 1; j <= i; j++) {
if (numbers[j-1] > numbers[j]) {
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
}
then loop through it again and find if the values[i]
is ==
to values[i+1]
Note: when you create your for loop make it 1 length shorter to compensate for values[i+1]
so it does not go out of bounds.
回答2:
You can use this code ,
int main()
{
int test[10] = {1,2,1,3,4,5,6,7,8,3,2};
int i,j,dupliCount = 0;
for (i =0; i<(sizeof(test)/sizeof(int));i++)
{
for(j=i+1;j<(sizeof(test)/sizeof(int));j++)
{
if (test[i] == test[j])
{
++dupliCount;
break;
}
}
}
printf("duplicate count %d",dupliCount);
}
回答3:
It took me some time to debug this. Because it should be int test[11] = {1,2,1,3,4,5,6,7,8,3,2}
not int test[10]
. Each element has a subscription of 0 to 10. So there's altogether 11 elements.
#include <stdlib.h>
#define LEN (11)
int test[LEN] = {1,2,1,3,4,5,6,7,8,3,2};
void sort(int n, int *test){//sort them, use whatever you like
int i,j,y;
for (i=0;i<n;++i){
for (j=i+1;j<n;++j)
if (test[i]>test[j]){
y=test[i];
test[i]=test[j];
test[j]=y;
}
}
}
int main(){
sort(LEN,test);//sort first
int cnt = 0 , i ;
for(i=1;i<LEN;++i)
cnt += (test[i]==test[i-1]);//count duplicates
printf("%d\n",cnt);//print result
}
回答4:
If memory space doesn't matter (I mean you're not constrained on memory usage) but running time is important and you know that the values in the array are not bigger than the size of the array, then Bucket Sort
sounds like the guy for the job. it will do the job in O(n) instead of O(nlgn) (if you decide to sort the array first).
int main()
{
int test[LEN] = {1,2,1,3,4,5,6,7,8,3,2};
int ndup = 0;
int bucket_array[LEN] = {0};
for (i = 0; i < LEN; i++) {
if (bucket_array[test[i]]++) {
ndup++;
}
}
printf("%d duplicates\n", ndup);
return 0;
}
i haven't compiled it but i guess it should do the job.
note: big thanks to jim balter for his useful comment.
来源:https://stackoverflow.com/questions/15893015/counting-duplicates-in-c