美文网首页
leetcode 26. Remove Duplicates f

leetcode 26. Remove Duplicates f

作者: 咿呀咿呀呦__ | 来源:发表于2017-12-28 19:30 被阅读0次

    Given a sorted array, 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 new length.
    
    class Solution:    
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if nums == []:
                return 0
    
            newTail = 0
    
            for i in range(1, len(nums)):
                if nums[i] != nums[newTail]:
                    newTail += 1
                    nums[newTail] = nums[i]
    
            return newTail + 1
    

    Complexity analysis:

    Time complextiy : O(n). Assume that n is the length of array. Each of i and j traverses at most n steps.

    Space complexity : O(1).

    相关文章

      网友评论

          本文标题:leetcode 26. Remove Duplicates f

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