【剑指offer】面试题3:数组中重复的数字

来源:互联网 发布:制作电子文档软件 编辑:程序博客网 时间:2024/06/11 10:50

题目一:

时间复杂度O(n), 空间复杂度O(n)

 

#include <iostream>using namespace std;#define nullptr 0bool duplicate(int numbers[], int len, int *duplication){    // 先判断输入是否合理    if(numbers == nullptr || len <= 0)        return false;         // 限定每个元素的大小在0 ~ n-1之间    for(int i = 0; i < len; i++)        if(numbers[i] < 0 || numbers[i] > len -1)            return false ;    for(int i = 0; i < len ;i++)    {        while(numbers[i] != i)        {            // 如果重复了            if(numbers[i] == numbers[numbers[i]])            {                *duplication = numbers[i];                return true;             }            // 交换numbers[i] numbers[numbers[i]]            int temp = numbers[i];             numbers[i] = numbers[temp];            numbers[temp] = temp;        }    }        return false ;}// 包含一个或多个重复的数字void test1(){    int a[] = {2, 3, 1, 0, 2, 5, 3};    int b ;     if(duplicate(a, sizeof(a)/ sizeof(int),&b))        cout << b << endl; }// 数组中不包含重复的数字void test2() {    int a[] = {1, 2, 3, 4, 5} ;    int b ;     if(duplicate(a, sizeof(a)/ sizeof(int),&b))        cout << b <<endl;    else         cout << "no duplication" <<endl;}// 无效的测试用例void test3() {    int *a = nullptr;     int b;     duplicate(a, 10, &b);}void test4() {    int a[] = {-1, 2};    int b;     duplicate(a, sizeof(a)/ sizeof(int), &b);}int main() {       test1();    test2();    test3();    test4();}


题目二: 









阅读全文
0 0
原创粉丝点击