(LeetCode)
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums =
Given input array nums =
[1,1,2]
,
Your function should return length =
2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.[code]
int removedup(vector<int> &s)
{
int index = 0;
int r = 0;
while(r < s.size()) {
while (r+1<s.size() && s[r+1] == s[r]) r++;
s[index ++] = s[r++];
}
return index;
}
Extended Problem 1:
Follow up for "Remove Duplicates": Duplicates are allowed at most twice?
For example,
Given sorted array nums =
Given sorted array nums =
[1,1,1,2,2,3]
,
Your function should return length =
5
, with the first five elements of nums being 1
, 1
, 2
, 2
and 3
. It doesn't matter what you leave beyond the new length.[code]
int reserve2dup(vector<int> &s)
{
int index = 0;
int r = 0;
int count = 0;
while( r< s.size()) {
while(r+1 < s.size() && s[r+1] == s[r]) {
r++; count ++;
}
if ( count >=2) {
s[index ++] = s[r];
count = 0; //clear for the subsequent sets
}
s[index++] = s[r++];
}
return index;
}
Extended Problem 2:
Follow up for "Remove Duplicates": Duplicates are allowed at most three times?
For example,
Given sorted array nums =
Given sorted array nums =
[1,1,1,2,2,2,2,3]
,
Your function should return length =
5
, with the first five elements of nums being 1
, 1
, 2
, 2, 2
and 3
. It doesn't matter what you leave beyond the new length.
now with problem 1 and problem 2, we can easily deduce that the solution is:
[code]
int reserve3dup(vector<int> &s)
{
int index = 0;
int r = 0;
int count = 0;
while( r< s.size()) {
while(r+1 < s.size() && s[r+1] == s[r]) {
r++; count ++;
}
if ( count >=3) {
s[index ++] = s[r];
s[index ++] = s[r-1];
s[index ++] = s[r-2];
count = 0 ; // clear for the subsequent sets
}
s[index++] = s[r++];
}
return index;
}
Extended Problem 3:
Follow up for "Remove Duplicates": Duplicates are allowed at most k-1 times?
Explanation omitted.
[code]
int reserveKdup(vector<int> &s, int k)
{
int index = 0;
int r = 0;
int count = 0;
while( r< s.size()) {
while(r+1 < s.size() && s[r+1] == s[r]) {
r++; count ++;
}
if ( count >= k) {
for( int i = 0; i< k; i++) s[index ++] = s[r -i];
count = 0 ; // clear for the subsequent sets
}
s[index++] = s[r++];
}
return index;
}