#C6904. Remove Duplicates from Sorted Array II

    ID: 50716 Type: Default 1000ms 256MiB

Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array II

You are given a sorted integer array nums of length n in non-decreasing order. Your task is to modify the array in-place such that each unique element appears at most twice while maintaining the relative order of the elements.

After performing the removal in-place, output the new length k of the modified array followed by the first k elements of the array.

Note: You must do this using only O(1) extra space.

The solution should implement the following logic:

  • If the number of elements is at most 2, then all elements keep their positions.
  • Otherwise, for every element starting from the third one, check if it is different from the element at position write_index - 2. If so, write this element at the current write_index and increment write_index.

The final output should be the length k followed by the first k elements of the modified array.

Formally, the checking condition can be expressed as:

$$\text{if } nums[i] \neq nums[write\_index - 2] \text{ then } nums[write\_index] = nums[i] $$

inputFormat

The input is read from stdin and has the following format:

n
num[0] num[1] ... num[n-1]

Where n (an integer) represents the number of elements in the array and each num[i] is an integer. If n is 0, no numbers follow.

outputFormat

The output should be printed to stdout in the following format:

k
nums[0] nums[1] ... nums[k-1]

Where k is the new length of the array after removing extra duplicates and the following line contains the first k elements of the modified array separated by spaces. If k is 0, the second line can be empty.

## sample
8
1 1 1 2 2 3 3 3
6

1 1 2 2 3 3

</p>