数组中超过一半的数

/* 29:> 数组中超过一半的数 排序 mid位置既是 [num][times]组合 */


//避免最多的数只达到一般: 比如134个数,中最多出现的数频率67
bool check(vector<int>gifts, int n, int num)
{
    int count = 0;
    for (int i = 0; i < n; ++i)
        if (gifts[i] == num)
            count++;
    return count > (n / 2);
}

int getValue(vector<int> gifts, int n)
{
    if (gifts.empty() || n <= 0)
        return 0;

    int Gurd[2] = { gifts[0],1 };
    for (int i = 0; i < n - 1; ++i)
    {
        if (gifts[i + 1] != gifts[i])
        {
            if (--Gurd[1] == 0)
                Gurd[0] = gifts[i + 1];
        }
        Gurd[1]++;
    }
    if (check(gifts, n, Gurd[0]))
        return Gurd[0];
    return 0;
}

你可能感兴趣的:(数组中超过一半的数)