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

时间:2013-06-21 11:00:20

标签: c++ algorithm recursion divide-and-conquer

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

例如: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;
    } 

1 个答案:

答案 0 :(得分:5)

这一行有错误:

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

检查应位于c索引,而不是l。除此之外,你的代码对我来说似乎没问题。

相关问题