# Remove Duplicates from Sorted Array II

### 描述​

Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?

For example, given sorted array A = [1,1,1,2,2,3], your function should return length = 5, and A is now [1,1,2,2,3]

### 代码 1​

# Remove Duplicates from Sorted Array II# Time complexity: O(n), Space Complexity: O(1)class Solution:    def removeDuplicates(self, nums: List[int]) -> int:        N = 2        if len(nums) <= N:            return len(nums)        slow = N        for fast in range(N, len(nums)):            if nums[fast] != nums[slow-N]:                nums[slow] = nums[fast]                slow += 1        return slow

### 代码 2​

// Remove Duplicates from Sorted Array II// Time Complexity: O(n), Space Complexity: O(1)public class Solution {    public int removeDuplicates(int[] nums) {        int n = nums.length;        int index = 0;        for (int i = 0; i < n; ++i) {            if (i > 0 && i < n - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i + 1])                continue;            nums[index++] = nums[i];        }        return index;    }};