Leetcode-Remove Duplicates from Sorted Array(Python)

1 Description(描述)

Given a sorted array nums, remove the duplicates in-place such that each element appear only once 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.
不要爲另一個數組分配額外的空間,只能通過修改輸入數組並且空間複雜度爲O(1)。

Example 1:
Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
函數應該返回length = 2,數字的前兩個元素分別爲1和2。

It doesn’t matter what you leave beyond the returned length.
在返回的長度之外留下什麼並不重要。

Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
函數應該返回length = 5,數字的前5個元素分別修改爲0、1、2、3和4。

It doesn’t matter what values are set beyond the returned length.
在返回的長度之外設置什麼值並不重要。

2 Solution(解決方案)

這道題很重要的一點就是要對傳入的數組進行操作,不可以通過別的方式,因此想法就很明確了,通過指針分別指向當前元素和下一位元素,如果相等則刪除,但兩個指針是相互挨着的,因此利用這個關係,使用一個指針即可。

    def removeDuplicates(nums):
        next = 1
        while next < len(nums):
            if nums[next - 1] == nums[next]:
                nums.pop(next)
            else:
                next += 1
        return len(nums)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章