# 3-6 easy lines, C++, Java, Python, Ruby

• Same simple solution written in several languages. Just go through the numbers and include those in the result that haven't been included twice already.

C++

``````int removeDuplicates(vector<int>& nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}
``````

Java

``````public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}
``````

Python

``````def removeDuplicates(self, nums):
i = 0
for n in nums:
if i < 2 or n > nums[i-2]:
nums[i] = n
i += 1
return i
``````

Ruby

``````def remove_duplicates(nums)
i = 0
nums.each { |n| nums[(i+=1)-1] = n if i < 2 || n > nums[i-2] }
i
end``````

• Beautiful solutions.

• Absolutely! The concisest ones!

• This post is deleted!

• I suggest you carefully read the name of the problem :-)

• You're right, it should be a sorted array, I was silly:)

• Brilliant solution!

• I am so glad that I checked this post.

• Very good use of two pointers!

• Brilliant and concise idea! Save lot of code

• Excellent,good job!

• Wow. I wrote it in 45 lines. There's always room for progress.

• Simple and elegant solution. I was doing all 3 pointers tricks in my solution.

• Damn, so smart

• Brilliant solution.

• great answer, very simple and smart solution

• Just want to confirm, this solution can be easily generalized to "at most K duplicates", right?

``````int removeDuplicates(vector<int>& nums, int k) {
int i = 0;
for (int n : nums)
if (i < k || n > nums[i-k])
nums[i++] = n;
return i;
}
``````

• brilliant solution.

• my straightforward code
...

``````int removeDuplicates(vector<int>& nums) {
if(nums.size()<3)
return nums.size();

int idx = 2;
for(int i=2;i<nums.size();++i)
{
if(nums[i]!=nums[idx-2])
nums[idx++] = nums[i];
}
return idx;
}
``````

};
...

• awesome!
what I can say is "Niu B!"

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.