1. 程式人生 > >LeetCode80 刪除排序陣列中的重複項II 2018.11.5

LeetCode80 刪除排序陣列中的重複項II 2018.11.5

題幹:

給定一個排序陣列,你需要在原地刪除重複出現的元素,使得每個元素最多出現兩次,返回移除後陣列的新長度。

不要使用額外的陣列空間,你必須在原地修改輸入陣列並在使用 O(1) 額外空間的條件下完成。

示例 1:

給定 nums = [1,1,1,2,2,3],

函式應返回新長度 length = 5, 並且原陣列的前五個元素被修改為 1, 1, 2, 2, 3 。

你不需要考慮陣列中超出新長度後面的元素。

示例 2:

給定 nums = [0,0,1,1,1,1,2,3,3],

函式應返回新長度 length = 7, 並且原陣列的前五個元素被修改為 0, 0, 1, 1, 2, 3
, 3 。 你不需要考慮陣列中超出新長度後面的元素。

說明:

為什麼返回數值是整數,但輸出的答案是陣列呢?

請注意,輸入陣列是以“引用”方式傳遞的,這意味著在函式裡修改輸入陣列對於呼叫者是可見的。

你可以想象內部操作如下:

// nums 是以“引用”方式傳遞的。也就是說,不對實參做任何拷貝
int len = removeDuplicates(nums);

// 在函式裡修改輸入陣列對於呼叫者是可見的。
// 根據你的函式返回的長度, 它會打印出陣列中該長度範圍內的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = len(nums)
        if l == 1:
            return 1
        pre, p, newl = 0, 0, 0
        while p < l - 1:
            if nums[p] == nums[p + 1]:
                while p < l - 1 and nums[p] == nums[p + 1]: #p < l - 1要先判斷,避免越界
                    p = p + 1
                nums[pre], nums[pre + 1] = nums[p], nums[p]
                pre, p, newl = pre + 2, p + 1, newl + 2
            else:
                nums[pre] = nums[p]
                pre, p, newl = pre + 1, p + 1, newl + 1
        if p == l - 1: #避免1,1,2,2,3型別情況漏掉3
            if nums[p] != nums[p - 1]:
                nums[pre] = nums[p]
                newl += 1
        return newl