80. Remove Duplicates from Sorted Array II

Leetcode

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/arrow-up-right

題目

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-placearrow-up-right 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 be 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 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-placearrow-up-right with O(1) extra memory.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
    assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted.

Example 1:

Example 2:

解答

  • 方法一

利用矩陣的 splice 方法

  • 方法二 - 快慢指針

慢指針指向重複兩個數字的後面那個數字,快指針遍歷所有矩陣

Runtime: 63 ms Beats 48.93% of users with JavaScript

Memory: 51.42 MB Beats 61.39% of users with JavaScript

  • 方法三 - 快慢指針進化版

前一個解法我們用 count 來記錄重複數值的數量是否有超過 2,但其實可以連 count 都不需要,原因是可以拿快指針去與慢指針的前一個元素進行比較

例如:

由於題目給的矩陣是由小到大排序過的,所以當 快指針所在的元素 慢指針的前一個元素 不相等時,這個 快指針所在的元素 一定不會是重複的,這時就可以把快指針所在的元素添加進矩陣

而如果 快指針所在的元素 慢指針的前一個元素 相等時,代表 快指針所在的元素 已經重複了,所以需要將快指針往後移動

參考資料

測資

Last updated