数组中出现的数字

版权声明: https://blog.csdn.net/qq_41880190/article/details/83546686

不修改数组进行查找:

#include <iostream>
#include<iomanip>   //引用 C++ 标准库头文件,调用函数 setw 格式化
using namespace std;
int countRange(const int* numbers, int length, int start, int end); //长度为 size 的数组,该函数将被调用 O(log(size)) 次;
int getDuplication(const int* numbers, int length)
{
    if(numbers == NULL || length <= 0)  //数组位空 || 长度小于 1
    {
        return false;
    }
    int start = 1;
    int end = length - 1;
    while(start <= end)
    {
        int middle = ((end - start) >> 1) + start;
        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 == NULL)
    {
        return 0;
    }
    int count = 0;
    for(int i = 0; i < length; i++)
    {
        if(numbers[i] >= start && numbers[i] <= end)
        {
            ++count;
        }
    }
    return count;
}
int main()
{
    std::cout << "Hello world" << std::endl;
    return 0;
}

修改数组:

#include <iostream>
#include<iomanip>
using namespace std;
void Swap(int*pa, int* pb)
{
    int tmp = *pa;
    *pa = *pb;
    *pb = tmp;
}
bool duplicate(int numbers[], int length, int* duplication)
{
    if(numbers == NULL || length < 0)
    {
        return false;
    }
    for(int i = 0; i < length; ++i)
    {
        if(numbers[i] < 0 || numbers[i] > length - 1)
        {
            return false;
        }
    }
    for(int i = 0; i < length; ++i)
    {
        while(numbers[i] != i)
        {
            if(numbers[i] == numbers[numbers[i]])
            {
                *duplication = numbers[i];
                return true;
            }
            Swap(&numbers[i], &numbers[numbers[i]]);
        }
    }
    return false;
}
int main()
{
    int array[] = {2, 3, 1, 0, 2, 5, 3};
    int size = sizeof(array);
    int* duplication = NULL;
    std::cout <<setw(2)<<duplicate(array, size, duplication)<< std::endl;
    std::cout << "Hello world" << std::endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41880190/article/details/83546686
今日推荐