计算C中的重复项 [英] Counting duplicates in C

查看:99
本文介绍了计算C中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将数组设置为:

test[10] = {1,2,1,3,4,5,6,7,8,3,2}

我想返回数字3,因为有重复项1,重复项2和重复项3.如何实现呢?效率无关紧要.

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.

推荐答案

首先,您必须对数组进行排序,以便于查找重复项.

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;
            }
        }
    }
}

然后再次遍历它,查找values[i]==还是values[i+1]

then loop through it again and find if the values[i] is == to values[i+1]

注意:创建for循环时,请使其长度缩短1长度以补偿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.

这篇关于计算C中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆