Array remove duplicate elements

前端 未结 12 1567
陌清茗
陌清茗 2020-11-27 16:17

I have an unsorted array, what is the best method to remove all the duplicates of an element if present?

e.g:

a[1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3]
         


        
12条回答
  •  我在风中等你
    2020-11-27 16:41

    This is a code segment i created in C++, Try out it

    #include 
    
    using namespace std;
    
    int main()
    {
       cout << " Delete the duplicate" << endl; 
    
       int numberOfLoop = 10;
       int loopCount =0;
       int indexOfLargeNumber = 0;
       int largeValue = 0;
       int indexOutput = 1;
    
       //Array to hold the numbers
       int arrayInt[10] = {};
       int outputArray [10] = {};
    
       // Loop for reading the numbers from the user input
       while(loopCount < numberOfLoop){       
           cout << "Please enter one Integer number" << endl;
           cin  >> arrayInt[loopCount];
           loopCount = loopCount + 1;
       }
    
    
    
        outputArray[0] = arrayInt[0];
        int j;
        for (int i = 1; i < numberOfLoop; i++) {            
            j = 0;
            while ((outputArray[j] != arrayInt[i]) && j < indexOutput) {
                j++;
            }
            if(j == indexOutput){
               outputArray[indexOutput] = arrayInt[i];
               indexOutput++;
            }         
        }
    
       cout << "Printing the Non duplicate array"<< endl;
    
       //Reset the loop count
       loopCount =0;
    
       while(loopCount < numberOfLoop){ 
           if(outputArray[loopCount] != 0){
            cout <<  outputArray[loopCount] << endl;
        }     
    
           loopCount = loopCount + 1;
       }   
       return 0;
    }
    

提交回复
热议问题