80. Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array II - LeetCode

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

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 1: Given 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 respectively.

It doesn’t matter what you leave beyond the returned length.

  • code
class Solution {
    public int removeDuplicates(int[] nums) {
        int left = 0, right = 0, count = 0;
        while (right < nums.length){
            if (count < 2){
                nums[left] = nums[right];
                left++;
                count++;
                right++;
                if (right < nums.length && nums[right] != nums[left-1]) count = 0;
            }else if (count == 2){
                while (right < nums.length && nums[right] == nums[left-1]){
                    right++;
                }
                count = 0;
            }
        }
        return left;
    }
}
  • code
class Solution {
    public int removeDuplicates(int[] nums) {
        int step = 0;
        for (int num: nums){
            if ((step < 2) || num > nums[step - 2]){
                nums[step] = num;
                step++;
            }
        }
        return step;
    }
}
  • code
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if len(nums) < 3:
            return len(nums)
        step = 2
        for i in range(2, len(nums)):
            if nums[i] != nums[step-2]:
                nums[step] = nums[i]
                step += 1
        return step

  • code
class Solution:
    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

  • code
var removeDuplicates = function(nums) {
    let i = 0;
    for (let n of nums){
        if (i < 2 || n > nums[i - 2]){
            nums[i++] = n
        }
    }
    return i
};