美文网首页
数组---6. Remove Duplicates from S

数组---6. Remove Duplicates from S

作者: 景景景景景景景色分明 | 来源:发表于2020-02-24 23:00 被阅读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项逐个更新了。

    相关文章

      网友评论

          本文标题:数组---6. Remove Duplicates from S

          本文链接:https://www.haomeiwen.com/subject/hmlmqhtx.html