函数返回排序数组中重复数字的计数

Function to return count of duplicate numbers in sorted array

本文关键字:数字 返回 排序 数组 函数      更新时间:2023-10-16

我想返回排序数组中重复值的数量。

例如:a={1,1,2,3,4,4},fratelli(n)应该返回2。(它们是1,1和4,4)

我试图使用递归方法,但它不起作用。它总是给我4。

我想问是否有人能帮助我更好地理解这种编程方法。非常感谢!

功能:

    #include <iostream>
    using namespace std;
    int fratelli(int a[], int l, int r)
    {
        if (l == r) return 0;
        else 
        {
            int c = (l+r) / 2;
            int n = fratelli(a, l, c) + fratelli(a, c+1, r);
            if (a[l] == a[l+1]) n++;
            return n;
        }
    }

    int main()
    {
        const int _N = 11;
        int array[_N] = { 1, 1, 2, 3, 5, 5, 7, 8, 8, 11, 12 };
        cout << "n" << fratelli(array, 0, _N-1);

        return 0;
    } 

您在这一行有一个错误:

if (a[l] == a[l+1]) n++;

检查应该在索引c处,而不是在l处。除此之外,你的代码对我来说似乎还可以。