Topic
An array of size n, in which the number belongs to the range [0, n-1], has indeterminate repeating elements, finds at least one repeating element, requires O (1) space and O (n) time.
Idea One
Looking for duplicate elements, it is easy to think of creating a hash table to complete, iterating through the array to map each element into a hash table. If this element already exists in the hash table, it means that this is a repeating element. This method makes it easy to find duplicate elements within O (n) time. But the topic requires space in O (1). Therefore, the method of using hash table is definitely not fit for the complexity of space. The number in the array in the title is within the range of [0, n-1], so the hash table size is n. So what we're actually going to do is hash the number of n ranges from 0 to n-1, and the hash table size is just n. It is not difficult for a classmate who is familiar with the sorting algorithm to find that this is very similar to a classic sort algorithm (cardinal sort). The time-space complexity of the base order is exactly the same as the problem. So try to use cardinality sorting to solve this question.
Code
/* ---------------------------------------------* Date: 2015-02-19 * SJF0115 * Title: Find duplicate element * Source: * Blog:-----------------------------------------------* * #include <iostream> #include <algorithm> using namespace STD;classSolution { Public:intIsreplication (intA[],intN) {if(N <=0){return-1; }//if for(inti =0; i < n;) {if(A[i]! = i) {//duplicate elements present if(A[i] = = A[a[i]]) {returnA[i]; }//ifSwap (A[i],a[a[i]]); }//if Else{++i; }//else}//for return-1; } };intMain () {solution solution;intNum[] = {6,1,4,7,5,3,6,2};intresult = solution. Isreplication (NUM,8);cout<<result<<endl; }
[classic face question] [Google] An array of size n, in which the number belongs to the range [0, n-1], with indeterminate repeating elements, find at least one repeating element