Remove Duplicates from Sorted Array II
- leetcode 80
- Medium
- Company Tag: Facebook
- Tags: Array, Two Pointers
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
For example, 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.
Previous Thinking
This problem should be quit similar to question remove duplicates from sorted array. The only difference is this problem allow the duplicate shows up twice. To make the solution flexible. Intuitively, I just add a variable to record the duplicate times.
However, remember the array is sorted. Instead of declaring a new varible, we can just intepret the condition to nums[i] != nums[index - 1]
.
C++ Solution
int removeDuplicates(vector<int>& nums){
if(nums.size() <=2) return nums.size();
int index = 1; //the assignment just starts start from the second position;
for(int i = 2; i < nums.size(); i++){
if(nums[i] != nums[index - 1])
nums[++index] = nums[i];
}
return index + 1;
}
Java Solution
public int removeDuplicates(int[] nums) {
if(nums.length < 3) return nums.length;
int index = 1;
for(int i = 2; i < nums.length; i++){
if(nums[i] != nums[index - 1])
nums[++index] = nums[i];
}
return index + 1;
}
Post thinking
From the title of this catagory of problems, we often think from how to Remove elements. We should notice that Remove sometimes means Re-Assign.