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.
Example :
Input: nums = [1,1,1,2,2,3] Output: 5, nums = [1,1,2,2,3,_] Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Table of Contents
Remove Duplicates From Sorted Array II Problem Solution
Problem Solution In Python
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
for num in nums:
while nums.count(num) > 2:
nums.remove(num)
return len(nums)
Problem Solution In Java
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length==0){
return 0;
}
int x=1,index=0;
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1] && x==1){
x++;
nums[index++]=nums[i];
}
else if(nums[i]!=nums[i+1]){
x=1;
nums[index++]=nums[i];
}
}
nums[index++]=nums[nums.length-1];
return index;
}
}
Problem Solution In C++
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<3) return nums.size();
int i =1;
while (i<nums.size()){
if(nums[i-1] == nums[i]){
if(i == nums.size()-1) return nums.size();
if(nums[i+1] == nums[i]) {nums.erase(nums.begin()+i);continue;}
}
i++;
}
return nums.size();
}
};
Problem Solution In C
int removeDuplicates(int* nums, int numsSize){
if(!numsSize)
return 0;
int len = 0, count = 1;
for (int i = 1; i < numsSize; i++)
{
if (nums[i] != nums[len])
{
len++;
nums[len] = nums[i];
count = 1;
}
else
{
count++;
if (count <= 2)
{
len++;
nums[len] = nums[i];
}
}
}
return len+1;
}