Title: All numbers in an array of length n are within the range of 0 to n-1. Some of the numbers in the array are duplicates, but I don't know how many numbers have been duplicated, and I don't know how many times each number repeats. Please find any duplicate numbers in the array.
Analytical:
Method One:
If you can take up extra space , you can constantly press the numbers in the array into the hash-table, go to the hash-table, and find out if there are duplicates. Space complexity O (n), time complexity O (n)
Method Two:
But if you can't take up extra space :
Assuming no repetition number, a[i] = i; i = 0,1, ..., n-1, if a[i]! = i, check a[i] is equal, if equal finds duplicates; otherwise, interchange a[a[i] and A[i]] [a[a[i]] = I, that is, the final position is reached because A[a[i] may still not be equal to I, continue to a[i] operation.
e.g.
[1,2,4,3,0,2]; A[0]! = 0, 1! = a[1], interchange 1 and 2,[2,1,4,3,0,2] 1 reached final position
[2,1,4,3,0,2] 2! = 0, 2! = a[2]; Exchange 2 and A[2],[2,1,4,3,0,2] 2 reached the final position
Exchanges 4 and 0,[0,1,2,3,4,2] found that both 0 and 4 reached their final position.
For the last 2,2! =5,2 = = A[2], so found duplicates
From the above example, it can be found that each element can reach the final position at most 2 times , time complexity O (n), Space complexity O (1)
#include <iostream>using namespace STD;voidSwapint&a,int&B) {inttemp = A; A = B; B = temp;}BOOLDuplicateintA[],intSizeint*duplication) {//Check input legitimacy if(A = = NULL | | size <=1)return false; for(inti =0; i < size; i++) {if(A[i] <0|| A[i] > size-1)return false; }//Find phase for(inti =0; i < size; i++) {//continuous to a[i] operation until a[i] = = I while(A[i]! = i) {if(A[i] = = A[a[i]]) {cout<< A[i] << Endl;return true;//Discovery Duplicates} swap (A[i], a[a[i]); } }return false;}intMain () {intA[] = {7,5,6,0,1,4,2,3};intSize =sizeof(a)/sizeof(a[0]);int*duplication = NULL;cout<< Duplicate (A, size, duplication) << Endl;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
51-repeated numbers in the array