Thought count (similar to the hash value)

// determines whether there are duplicate elements in the array, the idea is to use the most direct double loop determines (O (^ n-2));
// can be sorted first, comparison, but based on the comparison sort time complexity of at least O (the n-* logN).
// so, these ideas will not work. According restrictions subject, it is easy to think of the sort of count, time complexity is O (n), which of course meet the meaning of the questions, however, the counting sort used herein, is undoubtedly overkill.
// count sort, a key step is counted, the count present title can use to sort the count thought ( somewhat similar to a hash), the program code is as follows:

#include<iostream>
using namespace std;

void print(bool b)
{
if (b)
cout << "yes" << endl;
else
cout << "no" << endl;
}
typedef struct Hashtable
{
int value;
int count;
}hash;
bool hasTheSameNumber(int a[], int n)
{
int *p = new int[n];
//int *p=new hash[n];
int i;
for (i = 0; i < n; i++) //置0
{
p[i] = 0;
}
for (i = 0; i < n; i++) //开始计数
{
p[a[i] - 1]++;
//p[i].value=a[i]%n;
//p[i].count++;
}
for (i = 0; i < n; i++)
if (p[i] > 1) //有重复 //p[i].count
return true;
delete[] p;

return false;
}

int main()
{
int a[] = { 1, 3, 4, 2, 5 };
int b[] = { 1, 6, 2, 3, 4, 1 };

print(hasTheSameNumber(a, 5));
print(hasTheSameNumber(b, 6));
return 0;
}

Guess you like

Origin www.cnblogs.com/xcb-1024day/p/11334861.html