Method 1: Open up the auxiliary space
#include <vector> #include <algorithm> #include <iostream> #define LENGTH 10using namespace Std;void Unique () {int array[length]={1,1,1,2,2,4,4,6,6,6};int pre=array[0],cur=array[1];int temp[length];int k=0;int i=1;// Cur and I point to synchronous while (i<=9) {if (pre!=cur) {temp[k++]=pre;pre=cur;if (i!=9)///array The last one is special, need to judge Cur=array[++i];else ++i separately; End While Loop}else if (pre==cur) {pre=cur;cur=array[++i];}} The last element of the temp[k]=array[i-1];//array needs to be added to the result set for (int i=0;i<=k;i++) cout<<temp[i]<< ""; int main () {Unique (); return 0;}
Method 2: No need to open up auxiliary spaceThe problem of repeating elements in the array is often encountered in programming, and many people are now implementing them. However, some of the algorithms that have been implemented now require multiple arrays to be created, some of which are complex to write. After thinking and time, write out a most efficient algorithm, do not need to create an array multiple times, the algorithm is very simple. The code is as follows:
#include <vector> #include <algorithm> #include <iostream>using namespace std;int Unique (int array[], int arraylength) {int length=1;//array length after removing duplicate elements bool Isexist=false; The first element is definitely not duplicated, so the target array length is initially 1for (int i=1;i<arraylength;i++) {//compares the current value to the target array value one by one, and no duplicates are added to the destination array for (int j=0;j<length ; j + +) { if (Array[i]==array[j]) { isexist=true; } } if (!isexist) { array[length]=array[i]; length++; } Isexist=false; Default does not exist repeat} return length; } int main () {int array[]={1,1,2,2,3,4,4,6,6,6};int n=unique (array,10); for (int i=0;i<n;i++) Cout<<array[i] << ""; return 0;}
Remove duplicate elements from an array