Remove duplicate elements from an array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.