1. 程式人生 > >Leetcode 80.刪除排序數組中的重復項 II By Python

Leetcode 80.刪除排序數組中的重復項 II By Python

pri 為什麽 += print code 什麽 利用 長度範圍 leetcode

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

不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 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]);
}

思路

用了一個較為笨拙的方法:

利用\(collections.Counter\)

類來計算每個數字出現的次數,再將其中大於2的賦值為2,最後還原為list就好了

代碼

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        d = collections.Counter(nums)
        for key,value in d.items():
            if value > 2:
                d[key] = 2
        nums[:] = sorted(d.elements())
        return len(nums)        

雖然可以過,但是效率不高,看到最好的代碼是

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        i = 0
        for e in nums:
            if i < 2 or e != nums[i-2]:
                nums[i] = e
                i += 1
        
        return i

Leetcode 80.刪除排序數組中的重復項 II By Python