您的位置:首页 > 编程语言 > C语言/C++

C++ - 一个非递减数组,下标从0到n,元素的取值范围为从0到n的整数,判断其中是否有重复元素

2012-07-06 22:37 756 查看
#include <iostream>

#define NULL 0

using namespace std;

int hasDup(int a[], int n)
{
for(int i = 0; i <= n; ++i)
{
while(a[i] != i && a[i] != -1)
{
if(a[a[i]] == -1)
{
return 1;
}

a[i] = a[a[i]];
a[a[i]] = -1;
}

if(a[i] == i)
{
a[i] = -1;
}
}

return 0;
}

void main()
{
int a[10] = {0, 2, 3, 3, 3, 5, 6, 7, 8, 9};
int result = hasDup(a, 9);
if(result == 1)
{
cout << "The array does HAVE the duplicated nodes." << endl;
}
else
{
cout << "The array does NOT HAVE the duplicated nodes." << endl;
}
}

// Output:
/*
The array does HAVE the duplicated nodes.
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐