I was solving this problem : https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii. Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
I used the below code to solve this:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct getrid
{
bool operator()(int x)
{
static int count = 0;
static int prev = -1000001;
if(count == 0)
{
prev = x;
count++;
return false;
}
else
{
if(x == prev)
{
count++;
if(count > 2)
{
return true;
}
else
{
return false;
}
}
else
{
prev=x;
count=1;
return false;
}
}
}
};
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() < 3)
{
return nums.size();
}
auto last_iterator=std::remove_if(nums.begin(),nums.end(),getrid());
if(last_iterator == nums.end())
{
std::cout <<"Pointing to iterator pointed by end \n";
}
int total_element= last_iterator-nums.begin();
return total_element;
}
};
While this works fine perfectly for most test cases, this seems to fail for test cases when vector is [1,1] or [1,2,2] . Basically it seems for cases when last element has 2 occurrences.
But when I run the same on gdb online this seems to work perfectly fine. The returned value is 2 for vector [1,1] and 3 for [1,2,2].
Anyone can help me with why my test case is failing in leetcode ?
Code for gdbonline below
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct getrid
{
bool operator()(int x)
{
static int count = 0;
static int prev = -1000001;
if(count == 0)
{
prev = x;
count++;
return false;
}
else
{
if(x == prev)
{
count++;
if(count > 2)
{
return true;
}
else
{
return false;
}
}
else
{
prev=x;
count=1;
return false;
}
}
}
};
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
auto last_iterator=std::remove_if(nums.begin(),nums.end(),getrid());
if(last_iterator == nums.end())
{
std::cout <<"Pointing to iterator pointed by end \n";
}
int total_element= last_iterator-nums.begin();
return total_element;
}
};
int main()
{
std::vector<int> vec = {1,2,2};
Solution s;
int total_val = s.removeDuplicates(vec);
std::cout <<"total val returned is: " << total_val <<"\n";
return 0;
}
Thanks