剑指offer--数组中重复的数字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hanani_Jia/article/details/82704254

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

class Solution {

public:

// Parameters:

//        numbers:     an array of integers

//        length:      the length of array numbers

//        duplication: (Output) the duplicated number in the array number

// Return value:       true if the input is valid, and there are some duplications in the array number

//                     otherwise false

bool duplicate(int numbers[], int length, int* duplication) {

int* hash = new int[256];

int i = 0;

for (i = 0; i < 256; i++)

{

hash[i] = 0;

}

for (i = 0; i < length; i++)

{

hash[numbers[i]]++;

}

int count = 0;

for (i = 0; i < 256; i++)

{

if (hash[i]>1)

{

duplication[count++] = numbers[i];

return true;

}

}

return false;

}

};

对于这个题目我认为没什么可说的,虽然写起来比较复杂,但是我认为复杂在这个题目出的有问题,没太看懂,就是这个返回值,这个返回我以为只有一个true或者false,但是跑程序的时候发现他的输出不仅仅有这个还有输出的一个数值,再仔细一想才明白我们的duplication是一个指针,他应该就是一个数组了。他是用来存储重复的数字的,所以我认为我这里写的还是有点问题。这里不能直接返回true应该最后再返回true因为你可能会有不止一个的重复的数字。但是测试用例可能是给的不好,所以直接返回的话成功了。我是这个想的不知道是不是题目确实这样。

 思想还是用的我们的哈希,就不多说了。

猜你喜欢

转载自blog.csdn.net/Hanani_Jia/article/details/82704254
今日推荐