【剑指offer】题51:数组中重复的数字
程序员文章站
2023-12-27 18:53:33
...
bool duplicate(int numbers[], int length, int* duplication)
{
if (numbers==NULL||length<2||duplication==NULL)
{
return false;
}
vector<int> vec(length);
for (auto i = 0; i < length;++i)
{
if (vec[numbers[i]] != 0)
{
*duplication = numbers[i];
return true;
}
else
{
vec[numbers[i]] = 1;
}
}
return false;
}
bool duplicate(int numbers[], int length, int* duplication)
{
if (numbers==NULL||length<2||duplication==NULL)
{
return false;
}
for (auto i = 0; i < length;)
{
if (numbers[i] != i)
{
int j = numbers[i];
if (numbers[i] == numbers[j])
{
*duplication = numbers[i];
return true;
}
else
{
std::swap(numbers[i], numbers[j]);
}
}
else
{
i++;
}
}
return false;
}