Description

Remove Duplicates from Sorted Array II

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.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements
of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

在有序数组中删除重复的元素,每个元素允许重复一次(出现两次)。

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
func removeDuplicates(nums []int) int {
    length := len(nums)
    if length <= 2 {
        return length
    }

    readPointer, writePointer := 0, 0
    for readPointer < length {
        // 写入一次
        nums[writePointer] = nums[readPointer]
        writePointer++
        readPointer++

        if readPointer >= length {
            break
        }

        // 如果存在一个相同的,则再写入一次
        // 然后跳过后面重复的数字
        if nums[readPointer] == nums[writePointer-1] {
            nums[writePointer] = nums[readPointer]
            writePointer++
            readPointer++

            // 跳过重复的
            for readPointer < length && nums[readPointer] == nums[writePointer-1] {
                readPointer++
            }
        }
    }

    return writePointer
}