数组---6. Remove Duplicates from S

2020-02-24  本文已影响0人  景景景景景景景色分明

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.

Example

Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        x = 1
        for i in range(len(nums)-1):
            if(nums[i]!=nums[i+1]):
                nums[x] = nums[i+1]
                x+=1
        return(x)

Runtime: 80 ms, faster than 90.68% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 14.4 MB, less than 98.36% of Python3 online submissions for Remove Duplicates from Sorted Array.

相当于把前x项逐个更新了。

上一篇下一篇

猜你喜欢

热点阅读