title: In an array of length n, all numbers are in the range of 0 to n-1. Some of the numbers in the array are duplicates, but it is not known that several numbers have been duplicated and that each number repeats several times. Please find any duplicate numbers in the array. For example, if you enter an array of length 7 {2,3,1,0,2,5,3}, then the corresponding output is a repeating number of 2 or 3.
Analysis: In fact, this problem because of its limitations too much, so that the problem is lost generics, such as the number within the range of 0 to n-1, there is any meaning can be, can not be arbitrary array to check the operation. Let's take a look at how to solve this problem.
programme One:The time complexity is O (n*n) sequential scanning method. From the first scan to the last, proceed to the second one .... Must be able to find out.
Scenario Two:The time complexity is O (n) + auxiliary space O (n) hash table. Map each number to a hash table and scan it again to count the number of occurrences of all numbers. The hash table can then be scanned for the number of times the data appears in O (1). So we can find the duplicate numbers.
Programme III:the time complexity is 0 (N) and does not assist space.
The idea is this: sequentially scans each number of arrays. When scanning to a number labeled I, compare the number m is not equal to subscript I, such as, scan the next; if not, then compare it to the number labeled M, and if equal, find a return, and if not, exchange their values.
As an example of an array of a[7]={2,3,1,0,2,5,3}, the analysis is as follows:
The specific implementation code is as follows:
#include <iostream>using namespace Std;int arr[7]={2,3,1,0,2,5,3};void Swap (int &a,int &b) {int temp;temp =a;a=b;b=temp;} BOOL Duplicate (int array[],int length,int *duplication) {if (Array==null | | length<0) return false;for (int i=0;i< length;i++) {if (array[i]<0 | | array[i]>length-1) return false;} for (int i=0;i<length;++i) {while (array[i]!=i) {if (Array[i]==array[array[i]]) {*duplication=array[i];return true;} Swap (Array[i],array[array[i]);}} return false;} int main () {int Result;bool res;res=duplicate (arr,7,&result), if (res) cout<< "Duplicate number is:" <<result<< endl;elsecout<< "There are no duplicate numbers in the data! "<<endl;system" ("pause"); return 0;}
Operation Result:
Sword-Point offer: [51] Repeating number in array