I am trying to remove the duplicates from sorted array.Code is giving correct output for one test case but fails to give correct output for multiple test cases.I am getting correct output with other methods but what is wrong with this method? How can I solve this problem?
#include <iostream>
#include<bits/stdc .h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int a[n],i,k,temp,count;
for(i=0;i<n;i ){
cin>>a[i];
}
sort(a,a n);
count=0;
for(i=0;i<n;i ){
if(a[i-1]-a[i]==0){
temp = a[i];
count ;
for(k=i;k<n;k ){
a[k] = a[k 1];
}
}
}
for(i=0;i<n-count;i ){
cout<<a[i]<<" ";
}
cout<<endl;
}
}
CodePudding user response:
Variable length arrays like this
int a[n],i,k,temp,count;
is not a standard C feature. Instead you should use the standard container std::vector<int>
.
This if statement
if(a[i-1]-a[i]==0){
invokes undefined behavior when i
is equal to 0
.
The same problem exists in this for loop
for(k=i;k<n;k ){
a[k] = a[k 1];
}
when k is equal to n - 1
due to the expression a[k 1]
.
Also it is inefficient to copy all elements after the found duplicated element each time when such an element is found.
Pay attention to that there is the standard algorithm std::unique
that can be used instead of your loops.
If to use the for loop then you may implement something like the following
#include <iostream>
int main()
{
int a[] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t n = 0;
for ( size_t i = 0; i < N; i )
{
if ( i == 0 || a[i] != a[n-1] )
{
if ( i != n ) a[n] = a[i];
n;
}
}
for ( size_t i = 0; i < n; i )
{
std::cout << a[i] << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
1 2 3 4 5
CodePudding user response:
I see two major problems with your code, both are out-of-bounds reads from an array:
if(a[i-1]-a[i]==0)
will at one point be called with i==0
, accessing element a[-1]
.
And here:
for(k=i;k<n;k ){
a[k] = a[k 1];
}
in the last loop iteration, when k == n-1
array element a[n]
will be accessed, which is also an out-of-bounds access.