C++不修改数组找出重复的数字(剑指offer面试题3-2)

// 面试题3(二):不修改数组找出重复的数字
// 题目:在一个长度为n+1的数组里的所有数字都在1到n的范围内,所以数组中至
// 少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的
// 数组。例如,如果输入长度为8的数组{2, 3, 5, 4, 3, 2, 6, 7},那么对应的
// 输出是重复的数字2或者3。
/*******************解题思路**************************/
//将1—n的数字从中间的数字m分为两部分,前面一半为1—m,后面一半为m+1—n。如果
//1—m的数字的数目超过m个,那么这一半区间里一定包含重复的数字;否则,另一半
//m+1—n的区间里一定包含重复的数字。我们可以继续把包含重复数字的区间一分为二,
//直到找到一个重复的数字。这个过程和二分查找很类似,只是多了一步统计区间里数字
//的数目。
#include<iostream>
using namespace std;

int countRange(const int *numbers, int length, int start, int end);
// 参数:
//        numbers:     一个整数数组
//        length:      数组的长度
// 返回值:             
//        正数  - 输入有效,并且数组中存在重复的数字,返回值为重复的数字
//        负数  - 输入无效,或者数组中没有重复的数字
int getDuplication(const int *numbers, int length)
{
    if (numbers == nullptr || length <= 0)
    {
        cout << "输入数据为空,请重新输入!" << endl;
        return -1;
    }

    int start = 1;
    int end = length - 1;
    while (start >= end)
    {
        int middle = ((end - start) >> 1) + start;    //">>"表示移位运算符,n>>1表示向右移动一位,相当于除于2
        int count = countRange(numbers, length, start, middle);
        if (end == start)
        {
            if (count > 1)
                return start;
            else
                break;
        }
        if (count > (middle - start + 1))
            end = middle;
        else
            start = middle + 1;
    }
    return -1;
}

int countRange(const int *numbers, int length, int start, int end)
{
    if (numbers == nullptr || length <= 0)
    {
        return 0;
    }
    int count = 0;
    for (int i = 0; i < length; i++)
    {
        if (numbers[i] >= start && numbers[i] <= end)
        {
            count++;
        }
    }
    return count;
}

int main()
{
    int numbers[10] = { 1, 2, 8, 2, 4, 9, 7, 5, 6, 4 };
    int length = 10;
    int duplication = getDuplication(numbers, length);
    cout << duplication << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36427732/article/details/79635798