Home > Net >  Find unique element in sorted array using c
Find unique element in sorted array using c

Time:09-07

I am trying to find unique element from the array these is question

Input  : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output : arr[] = {1, 2, 3, 4, 5} 

They give me correct output but why they give 0 at the end in output:

these is my output:
{1,2,3,4,5,0}

Code:

#include<iostream>
using namespace std;
int main(){
    int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
    int n=sizeof(arr)/sizeof(arr[0]);
    int c=0;
    for(int j=0;j<=n;j  ){
        if(arr[j]!=arr[j 1]){
            cout<<arr[j];
            }


    }
   
} 

 

CodePudding user response:

Except for std::cout, you code is much more C than .

A more modern solution looks like this:

#include <iostream>
#include <algorithm>
#include <vector>
int main(){
    std::vector<int> arr {1, 2, 2, 3, 4, 4, 4, 5, 5};
    auto last = std::unique(arr.begin(), arr.end());
    arr.erase(last, arr.end());
    std::for_each(arr.begin(), arr.end(), [](int n){std::cout << n << std::endl;} );
} 

Try it on Godbolt.

CodePudding user response:

problem is in for loop becouse you use less or equal to n. you need to use just less then n becouse array starts from zero that means you asking for sixth element that do not have alocalizated in memory

now it should be correct

#include<iostream>
using namespace std;
int main(){
    int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
    int n=sizeof(arr)/sizeof(arr[0]);
    int c=0;
    for(int j=0;j<n;j  ){
        if(arr[j]!=arr[j 1]){
            cout<<arr[j];
            }


    }
   
} 
  • Related