80. Remove Duplicates from Sorted Array 2 - Medium
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 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 the 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.
Do not allocate extra space for another array. You must do this by modifying the input array in place with O(1) extra memory.
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 have underscores).
Constraints:
1 <= nums.length; <= 3 * 10**4
-10**4 <= nums[i] <= 10**4
nums is sorted in non-decreasing order.
Solution:
var removeDuplicates = function(nums) {
let k = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== nums[i+2]) {
nums[k] = nums[i];
k++;
}
}
return k;
}
Thoughts:
Again, I got the solution right the first time, even though it is a medium-style question! The answer is pretty much the exact same as leetcode problem 26. Remove Duplicates from Sorted Array. All you have to do is check that the current index value does not equal the next two index values because it can only be because it's sorted in order already, so if there are 3 numbers or more together, then they should be disregarded. I would give it a 9/10 purely based on the order in which I am doing these questions. I understand it and got it the first time but if I had a break from this type of question I might come back to it and struggle.
Comments
Post a Comment