Returns an integer array to calculate the number of deduplicated elements.
Eg:
Int A [] = {1, 2, 3, 1, 2, 3 };
The number of deduplicated elements is 3.
Method 1:
Whether the brute force check is repeated, and the complexity is O (n ^ 2)
For a [m], the order is compared to M-1], a [m-2]... a [0], all are not repeated, after deduplication, the number of elements + 1
Code:
Int uniq_element (int * a, int Len) {If (LEN <= 1) {return Len;} int num = 1; // Save the number of independent elements int I, J; // brute force comparison (I = 1; I <Len; I ++) {for (j = I-1; j> = 0; j --) {if (a [J] = A [I]) {break;} else {continue;} If (-1 = J) {num ++ ;}} return num;} int _ tmain (INT argc, _ tchar * argv []) {int A [] = {1, 2, 3, 3 }; int COUNT = uniq_element (A, sizeof (a)/sizeof (INT); cout <count <Endl; System ("pause"); Return 0 ;}
Method 2:
Sorting, deduplication, and complexity O (nlogn)
Step 1: Sort
Second part: deduplication
STL algorithms can be used.SortAndUnique
Code:
Int uniq_element (int * a, int Len) {If (LEN <= 1) {return Len;} // The array is saved to the vector container vector <int> myvector (, A + Len); vector <int>: iterator it; // sort (myvector. begin (), myvector. end (); // deduplication it = unique (myvector. begin (), myvector. end (); // reset sizemyvector. resize (IT-myvector. begin (); Return myvector. size ();}
Method 3:
Use the Binary Search Tree, complexity O (nlogn)
Insert data into the Binary Search Tree, and finally count the number of binary search tree data
STL containers can be usedSet
Code:
Int uniq_element (int * a, int Len) {If (LEN <= 1) {return Len;} set <int> myset; // insert setfor (INT I = 0; I <Len; I ++) myset. insert (a [I]); Return myset. size ();}
Method 4:
Use hash table, complexity O (N)-O (N ^ 2)
STL non-standard container hash_set can be used
Code:
Int uniq_element (int * a, int Len) {If (LEN <= 1) {return Len;} hash_set <int> myset; // insert hashsetfor (INT I = 0; I <Len; I ++) myset. insert (a [I]); Return myset. size ();}
There are still many methods, such as bitmap and bloom filter .......
Hope you can add more